Home > Blockchain >  Search in JSON file and show value from field next to it
Search in JSON file and show value from field next to it

Time:03-29

I'm searching in this JSON file: https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json

$search = '2054';
$file = file('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');
$found = false;

$jsonData = json_decode(json_encode($file),true);

foreach ($jsonData as $line) {
    if (strpos($line, $search) !== false) {
        $found = true;
        echo $line;
        echo $jsonData['Class'];
    }
}
if (!$found) {
    echo 'No match found';
}

I can now find "Id": 2054,

But I need the "Class": 1685, that comes with it.

Can someone help me to get that? Sorry i'm new to JSON and array searching & echoing. I have tried to find some solutions but it doesn't work. I think it's because of the complex way the array has been made. Thanks in advance!

CodePudding user response:

Not sure why you take a very nice json and you use it as a string to make your search. The most efficient and precise way is to loop the json object and find the items you want.

So first of all, instead of opening the file line-by-line, load it all together, using file_get_contents instead of file

$file = file_get_contents('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');

Then, instead of encoding/decoding, just decode it once so it's transformed in an object like this

$jsonData = json_decode($file);

Loop the resulting object with

foreach ($jsonData->cars as $car_id => $data) {
    foreach ($data->liveries as $liverie) {

This is a nested foreach since the source json has a 2-level nesting and your "Id" is find within the liveries objects.

Now within the last foreach you can use your search term to match the Id

if ($liverie->Id == $search) {

And you can access the Class you needed with

$liverie->Class;

Here's the overall code:

$search = '2054';
$file = file_get_contents('https://raw.githubusercontent.com/sector3studios/r3e-spectator-overlay/master/r3e-data.json');
$found = false;

$jsonData = json_decode($file);
foreach ($jsonData->cars as $car_id => $data) {
    foreach ($data->liveries as $liverie) {
        if ($liverie->Id == $search) {
            $found = true;
            echo $liverie->Id.PHP_EOL;
            echo $liverie->Class.PHP_EOL;
        }
    }
}

  • Related