合并数组忽略空值?

时间:2013-12-14 08:56:33

标签: php arrays multidimensional-array foreach

我试图将以下数组中的值提取到一个新数组中:

我收到了foreach命令的帮助,但现在无法合并两个数组,其中一个数组的值为null

原始数组是:http://pastebin.com/jeKVxpka

使用以下内容:

foreach ($arr['products']['product'] as $num) {

    $pid = $num['pid'];

    foreach($num['configoptions']['configoption']['0']['options']['option'] as $option)
        {
            $name = $option['name'];
            $yearlycosts = $option['pricing']['GBP']['monthly'];

            $namearr[] = $name;
            $yearlyarr[] = $yearlycosts;

            $peryear = array_combine($namearr, $yearlyarr);

        }

    $pricing[$pid] = array('cost' => $peryear);

}   

print_r($pricing);

我已经能够生成以下数组:

Array
(
    [2] => Array
        (
            [cost] => Array
                (
                    [1 Year] => 4.17
                    [2 Years] => 8.33
                    [3 Years] => 12.50
                    [4 Years] => 16.67
                    [5 Years] => 20.83
                )

        )

    [3] => Array
        (
            [cost] => Array
                (
                    [1 Year] => 40.83
                    [2 Years] => 8.33   <---
                    [3 Years] => 12.50     |--- These values shouldn't be here!
                    [4 Years] => 16.67     |
                    [5 Years] => 20.83  <---
                )

        )

    [4] => Array
        (
            [cost] => Array
                (
                    [1 Year] => 49.17
                    [2 Years] => 79.17
                    [3 Years] => 115.83
                    [4 Years] => 149.17
                    [5 Years] => 190.83
                )

        )

)

问题是,如果您查看原始数组,则产品ID [3]没有价格信息。对于产品ID [2],第2年到第5年已使用第2年到第5年的值填充。

我已经尝试过array_filterunset,但我无法弄清楚如何防止这种情况发生(或者为什么会发生这种情况)。

1 个答案:

答案 0 :(得分:2)

您需要在内部循环之前清空数组,因此不要保留主循环的上一次迭代中的值。你应该在内循环之外做array_combine

foreach ($arr['products']['product'] as $num) {

    $pid = $num['pid'];

    $namearr = array();
    $yearlyarr = array();

    foreach($num['configoptions']['configoption']['0']['options']['option'] as $option)
        {
            $name = $option['name'];
            $yearlycosts = $option['pricing']['GBP']['monthly'];

            $namearr[] = $name;
            $yearlyarr[] = $yearlycosts;

        }

    $peryear = array_combine($namearr, $yearlyarr);
    $pricing[$pid] = array('cost' => $peryear);

}   

print_r($pricing);