Reputation: 1775
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.
Upvotes: 2
Views: 56
Reputation: 2051
What you can do to make it a bit better is to:
Use foreach.
Use category by reference.
This way the code will look like this:
foreach ($products as $product) {
foreach ($categories as &$category) {
if (!isset($category['Products'])) {
$category['Products'] = array();
}
if ($product['category_code'] === $category['category_style_code']) {
$category['Products'][] = $product;
}
}
}
EDIT Having PHP > 5.5.0 you can use the following code to have the category_style_code column as key:
$keys = array_column($categories, 'category_style_code');
$categories = array_combine($keys, $categories);
This will combine an array that uses $categories as values and $keys as keys, where $keys we picked up all values in category_style_code column.
Upvotes: 1
Reputation: 837
I'd probably do this:
foreach( $prods as $prod ){
foreach ($cats as &$cat){
if ( $prod['category_code'] == $cat['category_style_code'] ) {
$cats['products'][] = $prod;
break;
}
}
}
And setting the category array key to the category code:
foreach( $cats as $k => &$cat ){
$cats[ $cat['category_style_code'] ] = $cat;
unset($cats[$k]);
}
I've tried that ampersand thing used in the other answer. Hopefully that works. If it doesn't there's another way.
Upvotes: 2