Skip to content
Advertisement

Group rows on one column and form nested subarray with other column

Here is the thing I trying deal with I have array which looks like this and have duplicates

    $products = [
[
    "product_name" => "Adidas1",
    "address" => "street 2"
],
[
    "product_name" => "Adidas2",
    "address" => "street 2"
],
[
    "product_name" => "Adidas3",
    "address" => "street 2"
],
[
    "product_name" => "Adidas4",
    "address" => "street 2"
],
[
    "product_name" => "Nike1",
    "address" => "street name1"
],
[
    "product_name" => "Nike2",
    "address" => "street name1"
]];

Result that I need to get is below . I did try different ways to do it but still can bring it to the finel result that have to come up

$final_result = [
[
    "address" => "street 2",
    "products" => [
        "addidas1",
        "addidas2",
        "addidas3",
        "addidas4",
        
    ]
],
[
    "address" => "street name1",
    "products" => [
        "Nike1",
        "Nike2",
       

    ]
]

any suggestion how to do it ?

here is my best solution that I tried

$stor_sorted = array();
foreach ($products as $product) {
    if (array_count_values($product) > 1) {
        $stor_sorted[] = ["address" => $product['address'], "items" => [$product['product_name']]];
    }
}

Advertisement

Answer

try this code

$products = [
        [
            "product_name" => "Adidas1",
            "address" => "street 2"
        ],
        [
            "product_name" => "Adidas2",
            "address" => "street 2"
        ],
        [
            "product_name" => "Adidas3",
            "address" => "street 2"
        ],
        [
            "product_name" => "Adidas4",
            "address" => "street 2"
        ],
        [
            "product_name" => "Nike1",
            "address" => "street name1"
        ],
        [
            "product_name" => "Nike2",
            "address" => "street name1"
        ]];

    $final_result = [];
    foreach ($products as $pr){
        $original_key = array_search($pr['address'], array_column($final_result, 'address'), true);
        if($original_key === false){
            $temp_array['address'] = $pr['address'];
            $temp_array['products'] =  [$pr['product_name']];
            $final_result[] =$temp_array;
        }else{
            $final_result[$original_key]['products'][] = $pr['product_name'];
        }
    }

your result will be in final_result array

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement