php - 添加/合并 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
我怎样才能做到这一点?
解决方案
我想你也可以使用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'];
推荐阅读
- c# - 添加 CosmosDB 实体,(无法解析租户类型实体的 iD)
- c++ - 在编译时检查指针内存布局:联合方法在 constexpr 中失败
- r - 在 R 中自动运行文件
- angular6 - How to render the ngx-quill-editor content without html tags on JHipster project?
- java - Android Notification Listener Service 自行启动
- matrix - Prolog - 编写名为 Adugo 的棋盘游戏
- html - 居中并在 Boostrap 4 中放置更大的文本区域
- java - Android Studio: Getters for editText
- ios - iOS 11.4 not asking Privacy Usage ( Privacy - Motion Usage Description has been set )
- asp.net - Entity Framework working with SQL Server views for ASP. NET web api