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.

\$\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.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.