从 JSON 输入中检索数组键

2022-08-30 21:50:47

我有这个数组:

$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');

我正在寻找一个PHP“for each”循环,该循环将检索下的键名,即:entries

id
name
age

我该怎么做?


答案 1

试试看

foreach($json->entries as $row) {
    foreach($row as $key => $val) {
        echo $key . ': ' . $val;
        echo '<br>';
    }
}

在$key您将获得键名,在val中您将获得值


答案 2

你可以做这样的事情:

foreach($json->entries as $record){
    echo $record->id;
    echo $record->name;
    echo $record->age;
}

如果作为函数中第二个参数的值传递,则可以将解码的值用作数组。truejson_decode