I have a query that returns an array or associative arrays of ids and years. It looks like this:
[{"id":8,"year":1950},{"id":9,"year":1950},{"id":8,"year":1951},{"id":9,"year":1951},{"id":8,"year":1952}]
There is a fixed number of ids, but they each have many years associated. I wrote the following script to turn the results of the query into a more simple associative array with the ids as keys and an array of years as the value.
$rows = array("8" => array(),"9" => array());
foreach(array_keys($rows) as $key){
foreach($results as $result){
if ($key == $result['id']){
array_push($rows[$key], $result['year']);
}
}
}
returns:
{"8":[1950,1951,1952],"9":[1950,1951]}
I would like to change this so that the initial $rows
array is not hard-coded (ie get the keys from the initial query). I would also like to avoid the nested foreach/foreach/if nastiness as well if possible.