Search code examples
phparrays

How to access keys and values of a multidimensional array


I try to give out the user_factions array with subs. (this is a part of a bigger array). Manually it works! with:

echo $stat['user_factions'][0]['online']

I tried and failed:

$stat = array (
'user_factions' => 
array (
0 => 
array (
  'online' => 30,
  'planets' => 185,
  'registred' => 138,
  'registred_today' => 1,
),
1 => 
array (
  'online' => 35,
  'planets' => 210,
  'registred' => 175,
  'registred_today' => 0,
),
),
);
      
$test= 0;
foreach ($stat['user_factions'][$test] as $key => $value){
echo $key .' = '. $value .', ';
$test++;
}

only got this:

online = 30, planets = 185, registred = 138, registred_today = 1, 

I want:

user_factions = 0, online = 30, planets = 185, registred = 138, registred_today = 1, 

user_factions = 1, online = 35, planets = 210, registred = 175, registred_today = 0,

Solution

  • You're trying to treat a foreach like a while loop. Since you have nested arrays, just use nested foreach:

    This:

    //                You're statically picking a child
    //                                |
    //                                v
    foreach ($stat['user_factions'][$test] as $key => $value){
        echo $key .' = '. $value .', ';
        $test++; // <-- This is having no effect.
    }
    

    Will become:

    foreach ($stat['user_factions'] as $faction) {
        foreach ($faction as $key => $value) {
            echo $key .' = '. $value .', ';
        }
    }