首页 > 解决方案 > 添加/合并 json 数组

问题描述

我正在构建一个工具来衡量网站的各种事情。

我通过每次检查建立了一系列信息。我将在没有大量代码的情况下概述下面的逻辑。

var report = [];


 //do a check for an ssl cert, if true...      
    report.push({
      "ssl": "true"
    });

//do a check for analytics tag, if true...
    report.push({
      "analytics": "true"
    });

//Then I run the google insights api and add results to the array...
    report.push(JSON.parse(data));

我的结果是这样...

{
    "ssl": "true"
},
{
    "analytics": "true"
},
{
    "captchaResult": "CAPTCHA_NOT_NEEDED",
    "kind": "pagespeedonline#result",
    "responseCode": 200,

现在我尝试通读它

$report = file_get_contents("json.json");
$json = json_decode($report, true);

给我..

[0] => Array (
    [ssl] => true
    )
[1] => Array (
    [analytics] => true
    )
[3=> Array ( [captchaResult] => CAPTCHA_NOT_NEEDED
[kind] => pagespeedonline#result
[responseCode] => 200)

不幸的是,我无法确定将生成数组 1 和 2 的顺序。所以如果我尝试回显这样的结果

echo $json[1]['ssl']

我会收到通知:未定义的索引:ssl。

理想情况下,我希望得到这样的数组:

[0] => Array (
    [ssl] => true
    [analytics] => true
    [captchaResult] => CAPTCHA_NOT_NEEDED
    [kind] => pagespeedonline#result
    [responseCode] => 200
)

因此,无论顺序如何,我都可以简单地回显:

  echo $json['ssl'];
  echo $json['analytics'];
  echo $json['captureResult']; etc etc

我怎样才能做到这一点?

标签: phparraysjsonarray-mergearray-push

解决方案


我想你也可以使用array_walk_recursive.

因为结果是单个数组,所以您应该确保不要对键使用重复值。

$result = [];
array_walk_recursive($arrays, function ($value, $key) use (&$result) {
    $result[$key] = $value;
});

print_r($result);

演示

那会给你:

Array
(
    [ssl] => 1
    [analytics] => 1
    [captchaResult] => CAPTCHA_NOT_NEEDED
    [kind] => pagespeedonline#result
    [responseCode] => 200
)

您可以使用例如获得您的价值echo $result['ssl'];


推荐阅读