download1002 2018-12-31 02:42
浏览 64

无法在PHP中循环遍历数组

I have an array that looks like this...

array(3) {
  [0]=>
  array(1) {
    [0]=>
    array(1) {
      ["@attributes"]=>
      array(1) {
        ["data"]=>
        string(23) "football games on today"
      }
    }
  }
  [1]=>
  array(1) {
    [0]=>
    array(1) {
      ["@attributes"]=>
      array(1) {
        ["data"]=>
        string(8) "football"
      }
    }
  }
  [2]=>
  array(1) {
    [0]=>
    array(1) {
      ["@attributes"]=>
      array(1) {
        ["data"]=>
        string(14) "football today"
      }
    }
  }
}

etc. Normally, I would just loop through this array to get the data that I need which would look like this...

$x=0;
foreach($array as $a){
    echo $a[$x][0]['@attributes']['data'].'<br>';
$x++;   
}

But, for some reason this very simple foreach loop will not output the data as I would expect. The loop returns nothing. I have add an

$x=0;
foreach($array as $d){
    echo $d[$x][0]['@attributes']['data'].'<br>';
  echo $x.'<br>';
$x++;   
}

echo $x; line into the code, and it will echo the incremental x value, so I know if is looping through the array properly.

It has been a very long few days of coding, so maybe I am just burnt out and missing somethings really simple. But I am not seeing it. Thank you for any help. It is much appreciated.

</div>
  • 写回答

1条回答 默认 最新

  • dqstti8945 2018-12-31 09:19
    关注

    If you do end up with deeply nested arrays you can gather the keys and values of the array 'leaves', by using array_walk_recursive:

    <?php
    
    $data = 
    [
        [
            [
                'wanted' => 'foo'
            ],
        ],
        [
            [
                'wanted'=> 'bar'
            ],
            'dead'=>'parrot'
        ]
    ];
    
    array_walk_recursive($data, function($v, $k) use (&$wanteds) {
        if($k==='wanted')
            $wanteds[]=$v;
    });
    var_export($wanteds);
    

    Output:

    array (
        0 => 'foo',
        1 => 'bar',
      )
    

    Note the conditional check on the leaf keys to only gather the attributes wanted.

    You can then loop through the generated array easily.

    评论

报告相同问题?

悬赏问题

  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接