添加 to/merge json 数组

Add to/merge json array

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

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

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

我怎样才能做到这一点?

您可以自己构建结果。

// base array default values
// we use $defaults because we assume the remainder of this task 
// will be performed for multiple websites inside of a loop
$defaults = array('ssl'=>false, 'analytics'=>false, 'captchaResult'=>'CAPTCHA_NOT_NEEDED', 'kind'=>'', 'responseCode'=>0) ;

// get a base copy of your array
$results = $defaults ;

// loop through your results
foreach($json as $values) {
    // get your key 
    $key = key($values) ;

    // get your value
    $results[$key] = $values[$key] ;
}

这将为您提供一组可预测的值。将默认值更改为正确的值

我想你也可以使用 array_walk_recursive

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

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

print_r($result);

Demo

那会给你:

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

您可以使用例如 echo $result['ssl'];

来获取您的值