将2个数组连接在一起代码改进

时间:2015-01-29 08:39:45

标签: php

有2个阵列。一个由类别和一个产品组成。每种产品都属于其特定类别。我想将每个产品加入到正确的类别(一个类别可以有多个产品)。每种产品都能找到'它的类别将属于此类别的产品阵列。

这是我的代码:

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]);
        }
    }
}

结果如下:

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
                        )
                )
        )
)

让我们说有很多类别和许多产品......您将如何优化此代码(或者以不同的方式执行可能会使用的PHP函数)?

编辑:我还想让结果数组索引成为其类别代码。

2 个答案:

答案 0 :(得分:2)

我可能会这样做:

foreach( $prods as $prod ){
    foreach ($cats as &$cat){
        if ( $prod['category_code'] == $cat['category_style_code'] ) {
             $cats['products'][] = $prod;
             break;
        }
    }
}

将类别数组键设置为类别代码:

foreach( $cats as $k => &$cat ){
     $cats[ $cat['category_style_code'] ] = $cat;
     unset($cats[$k]);
}

我已经尝试过在另一个答案中使用的&符号。希望这有效。如果没有,那就是另一种方式。

答案 1 :(得分:1)

你能做些什么才能让它变得更好:

  • 使用foreach。

  • 按引用使用类别。

这样代码看起来像这样:

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;
        }
    }
}

<强> 修改 拥有PHP&gt; 5.5.0您可以使用以下代码将category_style_code列作为键:

$keys = array_column($categories, 'category_style_code');
$categories = array_combine($keys, $categories);

这将组合一个数组,该数组使用$ categories作为值,$ keys作为键,其中$ keys我们选择了category_style_code列中的所有值。