I’m having difficulty constructing a multidimensional array based on queries fetched from a mysql database. The purpose is to prepare the result for json encoding. Having problems here.
Structure I’m aiming for:
Array (
[68] => Array (
[0] => Array (
[id] => 64
[description] => yada, yada, yada... )
[1] => Array (
[id] => 65
[description] => yada, yada, yada...)
[2] => Array (
[id] => 66
[description] => yada, yada, yada... ) )
[69] => Array (
[0] => Array (
[id] => 64
[description] => yada, yada, yada... )
[1] => Array (
[id] => 65
[description] => yada, yada, yada...)
[2] => Array (
[id] => 66
[description] => yada, yada, yada... ) )
...etc
)
From:
//this is a list of unknown length
$array_ids = (68, 69, 70, etc... ); // or:
Array (
[0] => 68
[1] => 69
[2] => 70
[3] => 71
etc..
)
//this is a known length
$array_contents = ( array ( array ( [id], [description]) ); // or:
Array (
[0] => Array (
[id] => 64
[description] =>yada, yada, yada... )
[1] => Array (
[id] => 65
[description] => yada, yada, yada... )
[2] => Array (
[id] => 66
[description] => yada, yada, yada... ) )
My attempt:
foreach($array_ids as $row){
$result = array($row=>array());
foreach($array_contents as $key => $value){
$result [$row][$key] = $value;
}
}
Result:
Array (
[68] => Array (
[0] => Array (
[id] => 64
[description] => yada, yada, yada... )
[1] => Array (
[id] => 65
[description] => yada, yada, yada...)
[2] => Array (
[id] => 66
[description] => yada, yada, yada... ) )
)
…and that’s where it stops. It doesn’t go on to the next row id of 69, 70, etc…
What am I doing wrong?
This line seems to be the problem:
Every pass through
$array_idsit’s completely wiping out$resultand repopulating it with one single item from$array_contents, rather than appending it to the end.Replacing it with this should work:
Here’s a full working version:
Here’s the output: