【问题标题】:How to access JSON element using regex or array index in PHP如何在 PHP 中使用正则表达式或数组索引访问 JSON 元素
【发布时间】:2017-03-28 23:30:46
【问题描述】:

我正在尝试使用 PHP 读取 JSON 元素 "unit""value"。但是,每个 JSON 中的某些 JSON 元素(“local/sysbench-cpu-1.0.0”、“m4.4xlarge-4.4.0-66-generic”)可能并不相同。这就是为什么我想使用正则表达式或数组索引来访问元素而不是特定的字符串:

{
    "title": "cputests-sysbench-cpu-100-m4-4xlarge-20170328",
    "results": {
        "local\/sysbench-cpu-1.0.0": {
            "arguments": "cpu performance benchmark",
            "units": "seconds",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "53.2386"
                }
            }
        },
        "": {
            "arguments": "Memory Usage Monitor",
            "units": "Megabytes",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "1355,1356,1357,1357,1358,1359,1358,1359,1359,1358,1357,1358,1369,1370,1374,1373,1374,1376,1370,1362,1359,1360,1358,1358,1357,1358,1360,1360,1359,1359,1362,1362,1362,1363,1362,1363,1366,1365,1369,1366,1365,1363,1362,1363,1362,1363,1363,1363,1368,1374,1373,1372,1372,1373"
                }
            }
        }
    }
}

如果我不使用正则表达式或数组索引,PHP 脚本可以工作:

<?php 
$string = file_get_contents("result.json"); <br>
$data = json_decode($string); <br>
//$data = json_decode($string, true);

//var_dump(json_decode($string)); <br>


print $data->{'results'}->{**'local/sysbench-cpu-1.0.0'**}->units; <br>
print "\n";<br>
print $data->{'results'}->{'local/sysbench-cpu-1.0.0'}->{'results'}->{'**m4.4xlarge-4.4.0-66-generic**'}->value; <br>

// print $data['results']['local/sysbench-cpu-1.0.0']['units']; <br>
// print "\n"; <br>
// print $data['results']['local/sysbench-cpu-1.0.0']['results']['m4.4xlarge-4.4.0-66-generic']['value']; <br>
?>

在使用json_decode($string, true) 时,任何尝试使用正则表达式代替字符串或数组索引都会失败。

【问题讨论】:

  • 为什么要使用正则表达式?如果json_decode 工作得很好。

标签: php arrays json regex


【解决方案1】:

您可以使用foreach 循环遍历results...

foreach ($json->results as $key => $results) {
  ...
  // access to $results->units

  foreach ($results as $x => $item) {
    ...
    // access to $item->value
  }
}

那么他们的密钥是什么就无关紧要了。类似的东西。

【讨论】:

  • 这当然是假设这是您将拥有的数据结构。
  • 第二个 foreach 不起作用。不确定我是否正确使用它。我将它用作嵌套循环。foreach ($data->{'results'} as $key => $results) { echo $results->units; foreach ($results as $x => $item){ echo $item->value; } }
【解决方案2】:

PHP 的 JSON 解析只返回一个普通的旧关联数组或一个对象。这些都不支持使用正则表达式作为查找。如果您坚持使用原生 PHP,则必须通过键和值来foreach

或者,您可以查看JsonPath 之类的内容,它允许您加载 JSON,然后使用看起来非常接近 shell globbing 的查询字符串:

$data = ['people' => [['name' => 'Joe'], ['name' => 'Jane'], ['name' => 'John']]];
$result = (new JSONPath($data))->find('$.people.*.name'); // returns new JSONPath

因此,在您的情况下,您的 find() 字符串将类似于 $.results.*.units 用于单位值,$.results.*.results.*.value 用于值。可能有一个更奇特的查询字符串可以同时返回单位和值。

【讨论】:

    猜你喜欢
    • 2012-08-29
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多