我有以下有效的JSON,其中包含导致我出现问题的密钥best_images
。
$json_array = {
"best_images":
[{
"id": "1",
"Title": "My Image 1",
"Photographer": "Kate Doe",
"Album": "Album 1",
"Imagefilename": "image1.jpg",
"Year": "2005",
"Size": "1.91 MB"
},
{
"id": "2",
"Title": "My Image 2",
"Photographer": "Jermaine Kavme",
"Album": "Album 2",
"Imagefilename": "image2.jpg",
"Year": "2012",
"Size": "5.13 MB"
},
{
"id": "4",
"Title": "My Image 4",
"Photographer": "Kate Doe2",
"Album": "Album 4",
"Imagefilename": "image4.jpg",
"Year": "2012",
"Size": "1.31 MB"
}
]
}
我想解码它,我使用以下方法:
$ obj = json_decode($ json_string,true);
但是,当我使用下面的代码来获取密钥时,我得到一个best_images
密钥而不是其他密钥。
foreach ($obj as $key => $value)
{
echo $key;
}
如何获得比第一个大键(实际上叫做什么)更深的东西来到达下面的键?
另外,如何将每个内部对象分开,以便将每个内部对象放入数据库行?
答案 0 :(得分:4)
如您所知,第一个数组键是“best_image”:
foreach ($obj["best_image"] as $key => $value)
{
echo $key;
}
否则你需要循环两次。
foreach ($obj["best_image"] as $mainkey => $arrObj)
foreach ($arrObj as $key => $value)
{
echo $key;
}
}
}
答案 1 :(得分:2)
使用递归函数:
function show_arr_r($arr, $level=0)
{
foreach ($arr as $k=>$v) {
for ($x=0; $x<$level $x++) print '.';
print "$k=";
if (is_array($v)) {
print "\n";
show_arr($k, $level+1);
} else {
print $k . "\n";
}
}
}
或者使用print_r或var_export。
但通常你想用数据做 - 只需添加更多[]来引用更深层的数组元素:
if ($obj["best_images"][1]["Photographer"]=="Kate Doe") {
或者...
if ($obj->best_images[1]->Photographer=="Kate Doe") {