【问题标题】:Add to/merge json array添加/合并 json 数组
【发布时间】:2018-06-07 11:33:31
【问题描述】:

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

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

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

我怎样才能做到这一点?

【问题讨论】:

标签: php arrays json array-merge array-push


【解决方案1】:

我想你也可以使用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']; 来获得您的价值

【讨论】:

    【解决方案2】:

    您可以自己构建结果。

    // 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] ;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2023-03-16
      • 2011-01-07
      • 2020-02-29
      • 2020-03-22
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多