Search code examples
phparraysmultidimensional-arrayconsolidation

How to consolidate duplicate elements of this array in PHP?


I have an array like this:

$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" => "")
);

It contains data from different orders, but as you can see an order can contain multiple purchased products, and each product can contain different 'components'. There's alot of duplicate data in this array, so I would like to turn it into this:

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

What would be a good way to do this?


Solution

  • Please use below code to make the solution what you want

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

    its should work!!