提问人:John Doe 提问时间:12/3/2010 最后编辑:Cedric IpkissJohn Doe 更新时间:12/28/2022 访问量:995391
如何使用动态键遍历 PHP 对象 [duplicate]
How to loop through PHP object with dynamic keys [duplicate]
问:
我尝试使用PHP解析JSON文件。但我现在被困住了。
这是我的JSON文件的内容:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
这就是我到目前为止尝试过的:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
但是因为我事先不知道名称(如 、)以及所有可用的键和值(如 )、,所以我认为我需要创建一些 foreach 循环。'John'
'Jennifer'
'age'
'count'
我希望能举个例子。
答:
尝试
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
评论
使用循环作为键值对循环遍历 JSON。进行类型检查以确定是否需要执行更多循环。foreach
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
评论
我不敢相信有这么多人在没有正确阅读 JSON 的情况下发布答案。
如果单独进行 foreach 迭代,则具有对象的对象。即使作为第二个参数传入,也有一个二维数组。如果你循环遍历第一维度,你就不能像那样回响第二个维度。所以这是错误的:$json_a
true
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
要呼应每个人的状态,请尝试以下操作:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
评论
file_get_contents("test.json");
test.json
pwd
/home/user/project/test.php
/home/user/project/json.json
/home/user
php project/test.php
project/test.json
若要循环访问多维数组,可以使用 RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
输出:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
评论
{'John':{'status':'waiting', 'Mary':{'status','nested'}}, 'Suzy':{'status:'waiting'} }
{'John':{'status':'waiting'}, 'Mary':{'status','nested'}, 'Suzy':{'status:'waiting'} }
Mary
John
你必须像这样给予:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
这给出了结果:
wait
active
评论
尝试一下:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
评论
尝试:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
评论
当你解码一个json字符串时,你会得到一个对象。不是数组。因此,查看所得到的结构的最好方法是对解码进行var_dump。(这个var_dump可以帮助你理解结构,主要是在复杂的情况下)。
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
评论
最优雅的解决方案:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
请记住,json 文件必须以 UTF-8 编码,而无需 BOM。如果文件具有 BOM,则json_decode将返回 NULL。
或者:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
评论
没有人指出你的开头“标签”是错误的,这完全超出了我的范围。您正在使用 {} 创建一个对象,而您可以使用 [] 创建一个数组。
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
通过此更改,json 将被解析为数组而不是对象。有了这个数组,你可以做任何你想做的事,比如循环等。
评论
回显所有 json 值的最快方法是使用循环中的循环,第一个循环将获取所有对象,第二个循环将获取值......
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
更多标准答案:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
输出为:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
评论
$data = json_decode(file_get_contents("db.json"), true);
array_keys()
foreach()
$val
试试这个
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
评论
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
评论
我正在使用以下代码将json转换为数组,
如果 JSON 有效,则运行良好,并将返回一个数组,
但是如果JSON格式不正确,它将返回,PHP
json_decode()
NULL
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
如果在格式错误的 JSON 的情况下,您只需要数组,那么您可以使用此函数,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
如果在格式错误的 JSON 的情况下,您想停止代码执行,那么您可以使用此函数,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>
评论
empty()
是不必要的开销。只需使用 .此外,这未能回答OP提出的问题。它不是“如何将值转换为数组”,也不是“如何检查JSON错误”。我将这篇文章标记为“不是答案”。!json_last_error()
评论
foreach($variable as $key => $val)
notices