如何在PHP中合并此数组的重复元素?

时间:2016-10-06 11:49:13

标签: php arrays multidimensional-array consolidation

我有一个这样的数组:

$array = array(
    0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
    1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
    2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
    3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);

它包含来自不同订单的数据,但正如您所看到的,订单可以包含多个已购买的产品,并且每个产品可以包含不同的组件'。这个数组中有很多重复数据,所以我想把它变成这个:

$array = array(
    0 => array(
        "order" => array(
            "ordernumber" => "1", "name" => "John"
        ),
        "products" => array(
            0 => array(
                "name" => "laptop",
                "components" => array("memory", "cpu")
            ),
            1 => array(
                "name" => "desktop",
                "components" => array("cpu")
            )
        )
    ),
    1 => array(
        "order" => array(
            "ordernumber" => "2", "name" => "Pete"
        ),
        "products" => array(
            0 => array(
                "name" => "monitor",
                "components" => array()
            )
        )
    )
);

这样做的好方法是什么?

1 个答案:

答案 0 :(得分:1)

请使用以下代码制作您想要的解决方案

<?php 

$array = array(
    0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
    1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
    2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
    3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);



$final_array = [];
foreach($array as $k=>$v){
    $final_array[$v['ordernumber']]['order']['ordernumber'] = $v['ordernumber'];
    $final_array[$v['ordernumber']]['order']['name'] = $v['name'];

    $final_array[$v['ordernumber']]['products'][$v['product']]['name'] = $v['product'];
    $final_array[$v['ordernumber']]['products'][$v['product']]['components'][] = $v['component'];
}

// You can skip this foreach if there will not metter of KEY of an array in your code!
$final_array = array_values($final_array);
foreach($final_array as $k=>$v){
    $final_array[$k]['products'] = array_values($final_array[$k]['products']);  
}


echo "<pre>";
print_r($final_array);

?>

它应该工作!!