Joel.O Joel.O - 1 month ago 10
PHP Question

PHP convert flat to nested multidimensional array in foreach loop

I have some data that is coming from a mysql query in a flat array this way:

0 => Array
indcode => "A00"
indlabel => "Code label text"
description => "More explanations"
1 => Array
indcode => "NA0"
indlabel => "Un-classified A"
description => "Un-classified A"
2 => Array (3)
indcode => "A01"
indlabel => "Code Label text"
description => "More explanations"
3 => Array (3)
indcode => "A02"
indlabel => "Code label text"
description => "More explanations"


I would like to nest it that way:

A00 => Array
indlabel => "Code label text"
description => "More explanations"
NA0 => Array
indlabel => "Un-classified A"
description => "Un-classified A"
A01 => Array
indlabel => "Code Label text"
description => "More explanations"
A02 => Array
indlabel => "Code label text"
description => "More explanations"


So in my CMS I found in use a very neat code which does the nesting :

foreach ($dimsDesc as $desc) {
$descriptions[$desc['indcode']][$desc['indlabel']] = $desc['description'];
}


That works but I didn't find how to keep the indlabel and description at the same level (= the other side of the equal sign).

Also, if you have links to some other examples or a good reference for this construct, it would be appreciated because I will use this a lot to build dynamic reports... And for now PDO queries are a bit out of my reach. I also used
array_column()
with
NULL
which works but I have more complex data structures incoming...

Answer

You're almost there, just change your foreach loop in the following way,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']]['indlabel'] = $desc['indlabel'];
    $descriptions[$desc['indcode']]['description'] = $desc['description'];
}

Or,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']] = array('indlabel' => $desc['indlabel'], 'description' => $desc['description']);
}

Here's the documentation,