Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

Access JSON objects value in PHP without a loop

I wonder how to access objects' values without a loop in a JSON file like this:

{
  "adresse": "",
  "longitude": "12.352",
  "latitude": "61.2191",
  "precision": "",
  "Stats": [
    {
      "id": "300",
      "carte_stat": "1154€",
    },
    {
      "id": "301",
      "carte_stat": "1172€",
    },
    {
      "id": "302",
      "carte_stat": "2293€",
    },
  ],
}

I'd like to target for example the object with id '301'. Using a loop I do like this:

foreach($result_json['Stats'] as $v) {

    if ($v['id'] == "301") {
        ...
    }

};

But How can I do without loop?

I tried things like this but in vain:

$result_json['Stats'][id='301']['carte_stat'];
$result_json['Stats']['id']->{'301'};

Thank yo for your help

question from:https://stackoverflow.com/questions/65924816/access-json-objects-value-in-php-without-a-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An alternative with array_filter. Get the first occurence of id 301:

$json = json_decode($json, true);

$result = current(array_filter($json['Stats'], function($e) {
    return $e['id'] == 301;
}));

print_r($result);

For/foreach will probably be faster. You shouldn't aim for "ligther code" when it will be a problem for readability or performance. Sometimes, more is less (problems).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...