PHP读取json文件的键值



试图读取json文件并为php变量赋值

我的json文件是这样的:

{
"123456": {
"fuelpump": {
"name": "Pump XX",
"address": "Address here",
"8493024" <-- I WANT THIS THE VALUE 8493024: {
"connectors": {
"8493024-1": {
"infohere": "more info here"
}
}
}
}
},
"456789": {
"fuelpump": {
"name": "Pump YY",
"address": "Address here",
"8374769" <-- I WANT THIS THE VALUE 8374769: {
"connectors": {
"8374769-1": {
"infohere": "more info here"
}
}
}
}
}

}

这是我的php代码的样子:

<?php
$jsonfile = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile);
foreach ($jsonitems as $location) {
$name = $location->fuelpump->name; //This works OK
$address = $location->fuelpump->address; // This ALSO OK
$fuelPumpno = $location->fuelpump[2]; //This doesnt work. Here i want the key names 8493024 and 8374769
}

如何获得键的名称"8493024"one_answers"8374769"?

您必须遍历fuelpump属性以查找值。
如果这是json对象的结构,并且它没有改变,你可以这样做:

foreach ($location->fuelpump as $key => $value) {
if ($key !== 'name' && $key !== 'address') {
$fuelPumpno = $key;
}
}

另一种方式
它过滤$location对象的键并获得结果的第一个元素:

$fuelPumpno = current(array_filter(array_keys(get_object_vars($location->fuelpump)), function($el) {
return $el !== 'name' && $el !== 'address';
}));

另一种方法是只过滤数值:

$jsonfile  = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile, true);
$pumpNo = [];
foreach ($jsonitems as $data) {
$pumpNo = array_merge($pumpNo, array_filter(array_keys($data["fuelpump"]), 'is_numeric'));
}
print_r($pumpNo);

返回

Array
(
[0] => 8493024
[1] => 8374769
)

最新更新