我有一个字符串:
$string='{"person":
[
"name":{"first":"Jhon","last":"Ramos"},
"phones":{"cel1":"809-555-4444","cel2":"809-444- 4444","home":"819-515-4434"},
"address":{"addr1":"adress numer one","addr2":"adress number two"}
]
}';
我想使用json解析字符串并打印所有子数组的名称,如: 名称 手机 地址
只是名字,而不是价值观。
我该怎么做?
感谢您的帮助。
答案 0 :(得分:0)
使用json_decode:
$string = '{"person":
[
"name":{"first":"Jhon","last":"Ramos"},
"phones":{"cel1":"809-555-4444","cel2":"809-444- 4444","home":"819-515-4434"},
"address":{"addr1":"adress numer one","addr2":"adress number two"}
]
}';
$result = json_decode($string, true);
foreach($result['person'] as $key => $val)
{
print_r($val);
}
答案 1 :(得分:0)
你的$ string不是json,所以你必须用$string = str_replace(array("[", "]"), array("{", "}"), $string);
然后代码为,
<?php
$string='{"person":
[
"name":{"first":"Jhon","last":"Ramos"},
"phones":{"cel1":"809-555-4444","cel2":"809-444- 4444","home":"819-515-4434"},
"address":{"addr1":"adress numer one","addr2":"adress number two"}
]
}';
$string = str_replace(array("[", "]"), array("{", "}"), $string);
$json = json_decode($string, true);
foreach($json["person"] as $key => $value)
echo $key."\n";
?>
输出为,
name
phones
address