Skip to content
Advertisement

Group rows of data by a column value and restructure into an associative multi-dimensionsl array

I am trying to change an indexed array of arrays into a new array structure. My data is as follows:

$arr = array( 
     array( "year" => 1921, "name" => "bob" ),
     array( "year" => 1944, "name" => "steve" ),
     array( "year" => 1944, "name" => "doug" ),
     array( "year" => 1921, "name" => "jim" ),
);

I would like to recreate a new array thats groups them into the same year. The best I can come up with is designating the year as the key so any row that has that year gets added to that key, but it’s not the output that I’m looking for. What I need is how it’s listed below.

"data": [
    {
       "year":"1921",
       "names": [ 
            { "name":"bob" }, { "name":"jim"} 
        ]
    },
    {
        "year":1944",
        "names": [
            { "name":"steve" }, { "name":"doug "} 
        ]
    }

Advertisement

Answer

You don’t need to pre-extract the unique years nor use conditions within nested loops. Just push the data into the result set using temporary first-level keys, then remove the temporary keys when finished looping.

This ensures unique years, but allows names to be duplicated.

Code: (Demo)

$arr = [
     ["year" => 1921, "name" => "bob"],
     ["year" => 1944, "name" => "steve"],
     ["year" => 1944, "name" => "doug"],
     ["year" => 1921, "name" => "jim"],
];

foreach ($arr as $item) {
    $result[$item['year']]['year'] = $item['year'];
    $result[$item['year']]['names'][] = ['name' => $item['name']];
}

echo json_encode(
         ['data' => array_values($result)],
         JSON_PRETTY_PRINT // for better visualization
);

Output:

{
    "data": [
        {
            "year": 1921,
            "names": [
                {
                    "name": "bob"
                },
                {
                    "name": "jim"
                }
            ]
        },
        {
            "year": 1944,
            "names": [
                {
                    "name": "steve"
                },
                {
                    "name": "doug"
                }
            ]
        }
    ]
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement