I need to generate an array whose keys are not pre-defined.
I have this array:
regions = [
{
"id":1,
"name":"Alaska",
"continent_id":5,
"owner_id":3,
....
},
{
"id":2,
"name":"Greenland",
"continent_id":5,
"owner_id":7,
....
}
I want to generate
$summary = [];
for ($i = 0; $i < count($owners); $i++) {
for ($j = 0; $j < count($regions); $j++) {
if ($owners[$i]['id'] == $regions[$j]['owner_id']) {
$summary[ $regions[$j]['continent_id'] ]++; <-- NEED HELP HERE
}
}
}
So I end up with $summary
containing a "key" for each continent that the user owns regions in, and how may in each continent.
The above does not work as it returns undefined index
. How do I generate the array keys on the fly and keep the count?
My expected output is:
$summary = ['1' => 12, '3' => 5, '5' => 7];
$summary[1] = 12;
$summary[3] = 5;
$summary[5] = 7;