I need to find the max population of an area code in an array that has duplicate area code keys in PHP [closed]

I need to find the max population of an area code in an array that has duplicate area code keys in PHP [closed]

I have an array that is pulling the following out of a CSV file

$results[] = array(
                    'areaCode' => $areaCode,
                    'city' => $data[$headers['name']],
                    'state' => $data[$headers['state_code']],
                    'population' => $data[$headers['population']],
                );

There are multiple instances of the same $areaCode. I need to pull out the instance of each $areaCode with the highest population and push it in a new array. For example, if I have two elements in the array that have $areaCode => 206 and three with $areaCode => 253, my new array should have one instance of 206 and 253 with the max populations and the others would stay in the original array.

I would need to go through each element in the original array (foreach) and see if the $areaCode first exists in the new array. If not, then I would put the first instance of that $areaCode in the new array. If so, I would need to check if the $maxPopulation of that areaCode is greater than what is already in the new array. If it is greater, replace it, if not – leave the one that is already in the new array.

Source: Symfony Questions

Leave a Reply

Your email address will not be published. Required fields are marked *