我试图解码JSON数据PHP然后输出到网站。如果我有以下内容:
{
"name": "josh",
"type": "human"
{
我可以这样做(在PHP中),显示或输出我的type
:
$file = "path";
$json = json_decode($file);
echo $json["type"]; //human
那么,如果我有以下内容:
{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}
我如何输出我的朋友ben
是什么type
?
使用foreach这样的循环并执行如下操作:
//specify the name of the friend like this:
$name = "ben";
$friends = $json["friends"];
//loop through the array of friends;
foreach($friends as $friend) {
if ($friend["name"] == $name) echo $friend["type"];
}
要以数组格式获得解码的数据,您将提供true
作为json_decode
的第二个参数,否则它将使用默认的object
表示法。当您需要查找特定的用户
$data='{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}';
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
if( $friend->name=='ben' )echo $friend->type;
}
function finduser($obj,$name){
foreach( $obj as $friend ){
if( $friend->name==$name )return $friend->type;
}
}
echo 'Tom is a '.finduser($friends,'tom');
try this,
$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
if($friend_name == $val->name)
{
echo "name = ".$val->name;
echo "type = ".$val->type;
}
}