回显多维数组

时间:2016-06-24 21:47:17

标签: php arrays multidimensional-array foreach

我有这个数组

 [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

我需要所有 [rewardItems] 数组中的 [name] (如果存在)。

我试过这样,但是没有结果,我做错了什么?

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

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

echo '

1 个答案:

答案 0 :(得分:0)

你已经有了一些嵌套循环来迭代这个结构。

<?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;
    }
  }
}