繁体   English   中英

数组在第二个foreach循环后丢失键

[英]Array lose keys after second foreach loop

我用的是什么:

$raw = file_get_contents('url');
$raw = json_decode($raw,true);

foreach($raw['data'] as $spell){
  var_dump($spell);
}

我得到了什么:

array(1) {
    ["image"]=> array(2){
        ["w"]=> int(48)
        ["h"]=> int(48)
    }
}

现在一切都很好。

但是当我使用第二个循环(因为超过1个键和值)时,如下所示:

foreach ($raw['data'] as $spell){
    foreach ($spell['image'] as $image) {
        var_dump($image);
    }
}

我明白了:

int(48) int(48)

没有其他的。
我期望得到:

array(2){
    ["w"]=> int(48)
    ["h"]=> int(48)
}

我究竟做错了什么?

使用第二个foreach循环,您将通过subArray $raw["data"]["image"] ,它只包含整数值而不是数组,因此它会打印出来。 将第二个foreach循环更改为: foreach ($spell['image'] as $key => $image) echo "$key => $value \\n"; 然后你看到了你的钥匙。

我用了

foreach ($raw['data'] as $spell){
    print $spell['image']['x'];
}

感谢Rizier123的答案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM