【问题标题】:Access JSON objects value in PHP without a loop [duplicate]在没有循环的情况下访问 PHP 中的 JSON 对象值 [重复]
【发布时间】:2021-05-01 14:56:09
【问题描述】:

我想知道如何在没有循环的 JSON 文件中访问对象的值,如下所示:

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

例如,我想定位 id 为“301”的对象。 使用循环我这样做:

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

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

};

但是没有循环怎么办?

我尝试过这样的事情但徒劳无功:

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

【问题讨论】:

  • 我不认为你可以用普通的 PHP。
  • 你不能。您需要知道存储该元素的确切数字索引,例如$result_json['Stats'][1].
  • 因为 $result_json['Stats'] 是一个数组,而“id”不是索引,您必须遍历它才能“查看”其中的值。但是为什么你不想要循环呢?
  • 感谢您的快速回答。不使用循环可以让我拥有更轻量的代码。

标签: php json


【解决方案1】:

array_filter 的替代方案。 获取 id 301 的第一次出现:

$json = json_decode($json, true);

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

print_r($result);

For/foreach 可能会更快。当它会成为可读性或性能问题时,您不应该以“更轻的代码”为目标。有时,多即是少(问题)。

【讨论】:

【解决方案2】:

您可以使用array_column() 索引Stats 来转换它。它比循环效率低,因为它会先转换整个数组,然后才能通过 id 访问它...

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

echo $stats['301'];

请注意,我必须修复您的 JSON,但我认为这是由于删除了问题不需要的数据。

【讨论】:

猜你喜欢
  • 2013-05-19
  • 2019-10-29
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2011-03-13
  • 1970-01-01
相关资源
最近更新 更多