[英]how to get json key value in php?
如何使用 PHP 获取此 JSON 中的所有键值? 我的 php 代码是:
<?php
$json = json_decode('{
"data": {
"after": [{
"google.com": "35"
}, {
"yahoo.com": "10"
}, {
"worldi.ir": "30"
}, {
"cnn.com": "554"
}, {
"scio.ir": "887"
}],
"before": [{
"bbc.com": "44"
}, {
"rtl.com": "15"
}, {
"quran.com": "9"
}, {
"lap.com": "12"
}, {
"search.com": "13"
}]
}
}');
foreach($json->data->after as $key => $value) {
echo "$key<br/>";
foreach(((array)$json->data->after)[$key] as $val) {
echo "$val<br/>";
}
}
?>
结果
0
35
1
10
2
30
3
554
4
887
不显示键值。 我想获取所有关键值。例如 google.com、yahoo.com、worldi.ir cnn.com 和...
after
是一个数组,因此在外部 foreach 循环中返回的$key
只是一个索引(一个整数)。 您应该在第二个 foreach 中再次包含$key => $value
以获取每个内部 object 的键。此外,您可以只对第一个 foreach 的$value
使用 foreach。 您不必再次指定整个密钥路径。
<?php
$json = json_decode('{
"data": {
"after": [{
"google.com": "35"
}, {
"yahoo.com": "10"
}, {
"worldi.ir": "30"
}, {
"cnn.com": "554"
}, {
"scio.ir": "887"
}],
"before": [{
"bbc.com": "44"
}, {
"rtl.com": "15"
}, {
"quran.com": "9"
}, {
"lap.com": "12"
}, {
"search.com": "13"
}]
}
}');
foreach($json->data->after as $key => $value) {
foreach($value as $k => $val) {
echo "$k<br/>$val<br/>";
}
}
?>
试试这个解决方案:
<?php
$json = json_decode('{
"data": {
"after": [{
"google.com": "35"
}, {
"yahoo.com": "10"
}, {
"worldi.ir": "30"
}, {
"cnn.com": "554"
}, {
"scio.ir": "887"
}],
"before": [{
"bbc.com": "44"
}, {
"rtl.com": "15"
}, {
"quran.com": "9"
}, {
"lap.com": "12"
}, {
"search.com": "13"
}]
}
}');
foreach($json->data->after as $key => $value) {
echo key($json->data->after[$key]);
foreach(((array)$json->data->after)[$key] as $val) {
echo "$val<br/>";
}
}
尝试这个:
<?php
$json = json_decode('{
"data": {
"after": [{
"google.com": "35"
}, {
"yahoo.com": "10"
}, {
"worldi.ir": "30"
}, {
"cnn.com": "554"
}, {
"scio.ir": "887"
}],
"before": [{
"bbc.com": "44"
}, {
"rtl.com": "15"
}, {
"quran.com": "9"
}, {
"lap.com": "12"
}, {
"search.com": "13"
}]
}
}');
foreach($json->data as $key1 => $value1) {
echo "$key1: \n";
foreach($value1 as $key2 => $value2) {
echo "$key2 -> ";
foreach($value2 as $key3 => $value3) {
echo "$key3 -> $value3\n";
}
}
}
?>
Output:
after:
0 -> google.com -> 35
1 -> yahoo.com -> 10
2 -> worldi.ir -> 30
3 -> cnn.com -> 554
4 -> scio.ir -> 887
before:
0 -> bbc.com -> 44
1 -> rtl.com -> 15
2 -> quran.com -> 9
3 -> lap.com -> 12
4 -> search.com -> 13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.