Question

I have JSON that looks like this (shortened for readability):

{
    "heroes": [
         {
            "name": "antimage",
            "id": 1,
            "localized_name": "Anti-Mage"
        },
        {
            "name": "axe",
            "id": 2,
            "localized_name": "Axe"
        },
        {
            "name": "bane",
            "id": 3,
            "localized_name": "Bane"
        }
    ]
}

I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.

$heroid = $myplayer['hero_id'];

$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);

foreach ($heroesarray as $parsed_key => $parsed_value) {
        if ($parsed_value['id'] == $heroid) {
    $heroname = $parsed_value['localized_name'];
    }
}
Was it helpful?

Solution

Easy. Just use json_decode(). Explanation follows the code at the bottom.

// First set the ID you want to look for.
$the_id_you_want = 2;

// Next set the $json.
$json = <<<EOT
{
    "heroes": [
         {
            "name": "antimage",
            "id": 1,
            "localized_name": "Anti-Mage"
        },
        {
            "name": "axe",
            "id": 2,
            "localized_name": "Axe"
        },
        {
            "name": "bane",
            "id": 3,
            "localized_name": "Bane"
        }
    ]
}
EOT;

// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);

// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
  echo '<pre>';
  print_r($decoded);
  echo '</pre>';
}

// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
  // Since this json is an array in another array, we need anothe foreach loop.
  foreach ($decoded_array_value as $decoded_key => $decoded_value) {
    // Do a comparison between the `$decoded_value['id']` and $the_id_you_want
    if ($decoded_value['id'] == $the_id_you_want) {
      echo $decoded_value['localized_name'];
    }
  }
}

Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:

Array
(
    [heroes] => Array
        (
            [0] => Array
                (
                    [name] => antimage
                    [id] => 1
                    [localized_name] => Anti-Mage
                )

            [1] => Array
                (
                    [name] => axe
                    [id] => 2
                    [localized_name] => Axe
                )

            [2] => Array
                (
                    [name] => bane
                    [id] => 3
                    [localized_name] => Bane
                )

        )

)

First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].

But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.

OTHER TIPS

json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.

$json = ''; // JSON string
$data = json_decode($json, true);

foreach($data['heroes'] as $hero) {
    if($hero['id'] === 2) {
        var_dump($hero['localized_name']);
        // Axe

        // This will stop the loop, if you want to keep going remove this line
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top