php - array pattern from parent to sub row

My array is:

[
 "0"=>["id"=>111,"name"=>"abc","value"=>"s1"],
 "1"=>["id"=>"","name"=>"","value"=>"s2"],
 "2"=>["id"=>"","name"=>"","value"=>"s3"],
 "3"=>["id"=>"222","name"=>"xyz","value"=>"a1"],
 "4"=>["id"=>"","name"=>"","value"=>"a2"],
 "5"=>["id"=>"","name"=>"","value"=>"a3"],
 "6"=>["id"=>"","name"=>"","value"=>"a4"]
];

I need this format of my array:

[
   "0"=>["id"=>111,"name"=>"abc","value"=>["s1","s2","s3"],
   "1"=>["id"=>"222","name"=>"xyz","value"=>"a1","a2","a3","a4"],
];

Answer

Solution:

Working Demo

<?php

$arr = [
 "0"=>["id"=>111,"name"=>"abc","value"=>"s1"],
 "1"=>["id"=>"","name"=>"","value"=>"s2"],
 "2"=>["id"=>"","name"=>"","value"=>"s3"],
 "3"=>["id"=>"222","name"=>"xyz","value"=>"a1"],
 "4"=>["id"=>"","name"=>"","value"=>"a2"],
 "5"=>["id"=>"","name"=>"","value"=>"a3"],
 "6"=>["id"=>"","name"=>"","value"=>"a4"]
];

// An array to store the results
$results = [];

// Store the index of the current results element
// Start with -1 because going to begin with an increment
$index = -1;

foreach ($arr as $element) {
    if ($element["id"] !== "") { // If contains an ID field

        // begin with increment; initial value must be -1
        $index++;

        // Create new results element
        $results[$index] = [ 
            "id" => $element["id"],
            "name" => $element["name"],
            "value" => [
                $element["value"],
            ],
        ];
    }
    else { // If does not contain an ID field

        // Add another "value" to existing element at $index
        $results[$index]["value"][] = $element["value"];
    }
}

var_dump(json_encode($results));

Output:

[
     {"id":111,"name":"abc","value":["s1","s2","s3"]},
     {"id":"222","name":"xyz","value":["a1","a2","a3","a4"]}
]

Source