-1

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;
TheRealPapa
  • 4,129
  • 7
  • 58
  • 139

1 Answers1

0

When you first encounter a particular value of 'continent_id' - or in fact any element of an array that hasn't previously been encountered, it's better to do an isset and then create it if required.

if ($owners[$i]['id'] == $regions[$j]['owner_id']) {
   if ( isset($summary[ $regions[$j]['continent_id'] ]) === false ) {
       $summary[ $regions[$j]['continent_id'] ] = 0;
   }
   $summary[ $regions[$j]['continent_id'] ]++;
}
Nigel Ren
  • 53,991
  • 11
  • 38
  • 52