Hertus Hertus - 5 months ago 10
PHP Question

Echo out a multidimensional array

I have this array

[result] => Array
(
[achievements] => Array
(
[0] => Array
(
[id] => 92
[achievements] => Array
(
[0] => Array
(
[id] => 6

[rewardItems] => Array
(
)
[49] => Array
(
[id] => 1956

[rewardItems] => Array
(
[0] => Array
(

[name] => inv_misc_book_11


I need the [name] (if there exist one) out of all the [rewardItems] arrays.

I tried it like that, but there are no results, what am i doing wrong?

foreach ($r['result']['achievements']['0']['achievements']['rewardItems'] as $item) echo '

', $item['name'], '.

echo '

Answer

You've got yourself some nested loops to iterate through in this structure.

<?php
$r = array(
 'result' => Array
    (
      'achievements' => Array
          (
            0 => Array
                (
                  'id' => 92,
                  'achievements' => Array
                      (
                        0 => Array
                            (
                              'id' => 6,

                              'rewardItems' => Array
                                  (
                                  )
                            ),
                        49 => Array
                            (
                              'id' => 1956,
                              'rewardItems' => Array
                                  (
                                      0 => Array
                                          (
                                              'name' => 'inv_misc_book_11'
                                          )
                                  )
                            )
                        )
                )
          )
    )
);

foreach ($r['result']['achievements']['0']['achievements'] as $achievement){
  if(!empty($achievement['rewardItems'])){
    foreach ($achievement['rewardItems'] as $item){
      echo "$item[name]<br/>".PHP_EOL;
    }
  }
}