-1

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'};
7
  • 3
    I don't think you can with plain PHP. Commented Jan 27, 2021 at 18:06
  • 3
    You can't. You would need to know the exact numeric index at which that element is stored, e.g. $result_json['Stats'][1]. Commented Jan 27, 2021 at 18:07
  • 3
    since $result_json['Stats'] is an array and "id" is not a index, you must loop through it to "see" the values inside it. But why do you don't want loop? Commented Jan 27, 2021 at 18:09
  • Thank you for your quick answers. Not using loops would have allowed me to have a lighter code. Commented Jan 27, 2021 at 18:18
  • 1
    Does this answer your question? PHP - find entry by object property from an array of objects Commented Jan 27, 2021 at 18:55

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Already demonstrated here: stackoverflow.com/a/55151946/2943403
0

You could index the Stats using array_column() to convert it. It's less efficient than a loop as it will first convert the entire array before you can access it by the id...

$stats = array_column($result_json['Stats'], "carte_stat", "id");

echo $stats['301'];

Note that I have to fix your JSON, but I assume this was due to chopping out data not needed for the question.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.