There are 2 arrays. One that consists of Categories and one of Products. Each product pertains to its specific category. I want to join each product to its right category (a category can have multiple products). Each product that 'finds' its category will go in this category's products array.
Here's my code:
for ($i = 0; $i < count($prods); $i++)
{
for ($u = 0; $u < count($cats); $u++)
{
if ($prods[$i]['category_code'] === $cats[$u]['category_style_code'])
{
if ( !isset($cats[$u]['products']) )
{
$cats[$u]['products'] = array();
}
array_push($cats[$u]['products'], $prods[$i]);
}
}
}
It results in something like:
Array
(
[0] => Array
(
[id] => 1
[category_style_code] => GA
[products] => Array
(
[0] => Array
(
[id] => 1
[default_price] => 37.50
[category_code] => GA
)
[1] => Array
(
[id] => 2
[default_price] => 15.00
[category_code] => GA
)
)
)
)
Let's say there are many categories and many products... How would you optimize this code (or do it differently maybe there are PHP functions which could be used) ?
Edit: I also want to make the resulting array indexes be the its category code.