php - php解析JSON子数组
问题描述
我在 PHP 中有一个 JSON 字符串:
$casedata = "{\"id\":4823,\"status\":2,\"steps\":12,\"error\":\"catched error playing testcase\",\"result\":\"\",\"sublog\":[{\"step\":8,\"message\":\"corpus.invalidState.2.getBlockedRegionsForUnit\"},{\"step\":10,\"message\":\"corpus.invalidState.2.getBlockedRegionsForUnit\"}]}";
我尝试用
$array = json_decode($casedata,true);
不,我通过以下键遍历:
foreach($array as $key => $value){
if(is_array($value)){
echo "Array";
}else{
echo "Content: ".$key." / ".$value." <br/>";
}
}
输出是
Content: id / 4823
Content: status / 2
Content: steps / 12
Content: error / catched error playing testcase
Content: result /
Array
工作正常。但是如何从子数组“sublog”中获取 $key 和 $value 呢?我试过作为样本:
foreach($array as $key => $value){
if(is_array($value)){
echo "Array";
foreach($value as $sub => $value2){
echo "Sub: ".$sub." / ".$value2." <br/>";
}
}else{
echo "Content: ".$key." / ".$value." <br/>";
}
}
但这不起作用。我在这里想念什么?
解决方案
您的内部数组是一维数组,而不是关联数组。
尝试使用
foreach($array as $key => $value){
if(is_array($value)){
echo "Array";
$count = count($value);
for($i=0;i<$count;i++) {
echo $value[i]['step']; // <---
}
}
}else{
echo "Content: ".$key." / ".$value." <br/>";
}
}
推荐阅读
- java - 单击事件在使用 Selenium 和 Java 的 MAC OS Safari 13.05 中不起作用
- javascript - 基于电子表格中的值的自定义日期和时间的 Google Apps 脚本基于时间的触发器
- angular - Angular 8 无法导入多个嵌套组件
- c++ - 使拉普拉斯展开更高效
- arrays - 将列表中的数组相乘
- jenkins - 如何将可扩展选择参数类型传递给 Jenkins 管道?
- neo4j - 通过排序和限制 Cypher Neo4J 中的中间节点数量来获取路径
- python - 无法将菜单项获取到模板
- css - 根据某些条件更改 TreeNode 的颜色;使用 antd React 库中的树
- python - 在 Visual Studio 之外,Python 脚本要慢得多