我有一个json文件,名称如下:“ brands.json”
{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}
我在网上看了一些示例并获得了这段代码
<?php
$read = file_get_contents("report.json");
$json = json_decode($read, true);
foreach($json as $key => $val){
if(is_array($val)){
echo "$key : <br>";
foreach($key as $k => $v){
echo "$k => $v<br>";
}
}
else {
echo "$key => $val<br>";
}
}
?>
我可以打印出
标题=>品牌列表
版本=> 1
耐克:
匡威:
冠军:
但是我想在这些品牌中使用阵列。我当时正在考虑在if语句中有一个foreach
循环。但是,它返回错误
nike:警告:为foreach()提供了无效的参数。
有些资源建议做类似$json->nike as $item => $v
的事情,但这将是多余的,因为我也有反向和冠军数组。如果有人可以引导我获得良好的资源或提供代码示例,将不胜感激。
预期表 耐克:
类型|尺寸颜色
鞋子| 10 |黑色
衬衫| S |黑色
答案 0 :(得分:0)
创建功能来缓冲输出并显示它
$read = '{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}';
$json = json_decode($read, true);
// this function will run recursively
function display($val){
// create output buffer variable
$output = "";
// check is array or not
if(is_array($val)){
// check is multimensional or not
if(isset($val[0])){
foreach($val as $v){
$output .= "<br/>".display($v);
}
}else{
foreach($val as $k => $v){
$output .= $k." => ".display($v)."<br/>";
}
}
}else{
// append output if it just a value
$output .= $val;
}
return $output;
}
echo display($json);
?>