John Davidson

php - Create inverted map of many-to-many data within a multidimensional array

0 comments
Message:


I am trying to create a new associative array where categories contain multiple items. My input array has the opposite orientation where individual items refer to multiple categories.


Input:


$items = [
["itemName" => "Hat", "price" => 10.99, "categories" => ["apparel", "head"]],
["itemName" => "Scarf", "price" => 7.99, "categories" => ["apparel", "neck"]],
["itemName" => "Watch", "price" => 19.99, "categories" => ["jewelry", "electronics"]],
["itemName" => "Necklace", "price" => 99.99, "categories" => ["jewelry", "neck"]],
["itemName" => "Headphones", "price" => 29.99, "categories" => ["head", "electronics"]]
];

Desired result:


[
'apparel' => ['Hat', 'Scarf'],
'head' => ['Hat', 'Headphones'],
'neck' => ['Scarf', 'Necklace'],
'jewelry' => ['Watch', 'Necklace'],
'electronics' => ['Watch', 'Headphones']
]

My code:


include_once("./array.php");

$categories = [];
$categoryMap=array();
#map to find with the category as the key then the item as the value
foreach ($items as $key => $value) {
# code...
$currentCategories = $value['categories'];
for ($i = 0; $i < sizeof($currentCategories); $i++) {
# code...
// if not in keys for the categoryMap then initialize with the key with a value of an empty array
// otherwise just add the the array of values using that keys

// visual of how it should be
// [
// 'buger':['bun','tomato','sauce']

// ]

array_push($categories, $currentCategories[$i]);
}
}
$categories = array_unique($categories);


My Answer:
'item1' => ['category1', 'category2'],
'item2' => ['category2', 'category3'],
'item3' => ['category1', 'category3'],
];

// Initialize an empty array to store the inverted map
$categories = [];

// Loop through each item in the input array
foreach ($items as $item => $itemCategories) {
// Loop through each category for the current item
foreach ($itemCategories as $category) {
// Check if the category already exists in the inverted map
if (!isset($categories[$category])) {
// If not, create a new key with an empty array as its value
$categories[$category] = [];
}
// Add the current item to the category's array
$categories[$category][] = $item;
}
}

// Output the inverted map
print_r($categories);

Output:
Array
(
[category1] => Array
(
[0] => item1
[1] => item3
)

[category2] => Array
(
[0] => item1
[1] => item2
)

[category3] => Array
(
[0] => item2
[1] => item3
)
)

Rate this post

5 of 5 based on 7840 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us