2
\$\begingroup\$

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.

asked Apr 17, 2015 at 18:10
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

By iterating through array_keys($rows), you are not using the $results associative array effectively. You should be able to just write this:

foreach ($results as $result) {
 $rows[$result['id']][] = $result['year'];
}

Also, there is no need to call array_push() if you are appending just one item. You can just assign $rows[] = with no index to indicate that you want to append one element.

answered Apr 17, 2015 at 18:27
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.