数组在第二次 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)
}
我做错了什么?
With the second foreach loop you go through the subArray
$raw["data"]["image"]
which only contain integer values and not
arrays, so it prints those. Change the second foreach loop to:
foreach ($spell['image'] as $key => $image) echo "$key => $value
\n";
Then you see your key.
我用过
foreach ($raw['data'] as $spell){
print $spell['image']['x'];
}
感谢 Rizier123 的解答!
我用的是:
$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)
}
我做错了什么?
With the second foreach loop you go through the subArray
$raw["data"]["image"]
which only contain integer values and not arrays, so it prints those. Change the second foreach loop to:foreach ($spell['image'] as $key => $image) echo "$key => $value \n";
Then you see your key.
我用过
foreach ($raw['data'] as $spell){
print $spell['image']['x'];
}
感谢 Rizier123 的解答!