如何在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" => "")
);

它包含来自不同订单的数据,但是如您所见,一个订单可以包含多个购买的产品,并且每个产品可以包含不同的“组件”。这个数组中有很多重复的数据,所以我想把它变成这样:

$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()
            )
        )
    )
);

什么是做到这一点的好方法?

阿肖克·钱德拉帕尔(Ashok Chandrapal)

请使用下面的代码使解决方案成为您想要的

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

?>

它应该工作!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章