0

I need to find $str in JSON

find name and result show age in JSON

{
“ID": {
“1": {
“name": A,
“age": “16"
},
“2": {
“name": B,
“age": “17"
},
}
}

I try put $str with name and need result output age

e.g.

input A output 16

my code is

$str = ‘A’;
$data = json_decode(file_get_contents('inJSON'));

foreach($data as $item) {
foreach($item->ID as $ID) {
if(ID->name ==  $str) {
echo age;
break;
}
}
}

didnt work

ps. sorry my English is not good.

DNXZ
  • 13
  • 2
  • Please edit your code to be well formatted, and make it more clear what isn't working about your code. What do you want it to do? What is it currently doing? Thank you. – Max von Hippel Dec 03 '17 at 04:32
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – localheinz Dec 03 '17 at 09:36

1 Answers1

0

You have invalid JSON (invalid string quoting, trailing commas), and your data traversal and variable referencing is faulty (you miss preceding dollar signs).

<?php
$json = <<<JSON
{
    "ID": {
        "1": {
            "name": "A",
            "age": "16"
        },
        "2": {
            "name": "B",
            "age": "17"
        }
    }
}
JSON;

$data = json_decode($json);

$getAgeByName = function ($name) use ($data) {
    foreach($data->ID as $person) {
        if($person->name == $name) {
            return $person->age;
        }
    }
};

var_dump($getAgeByName('A'));
var_dump($getAgeByName('B'));
var_dump($getAgeByName('C'));

Output:

string(2) "16"
string(2) "17"
NULL

Tips:

Check the return of json_decode. If NULL is returned the JSON cannot be decoded or the encoded data is deeper than the recursion limit.

If you are more comfortable working with arrays, pass json_decode true as the second argument.

Progrock
  • 7,373
  • 1
  • 19
  • 25