Home > other >  PHP read json file key value
PHP read json file key value

Time:05-20

Trying to read a json file and assign values to php variables.

My json file looks like this:

{
"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"
                }
            }
        }
    }
}

}

This is how my php code is looking:

<?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
}

How can i get the name of the keys "8493024" and "8374769"?

CodePudding user response:

You have to loop over the fuelpump properties to find the value.
If that is the structure of the json object, and it does not change, you can do with this:

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

Another way
it filters the keys of the $location object and get the first element of the result:

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

CodePudding user response:

Another approach is to filter only numeric values:

$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);

It returns

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