json,php - 从数组

时间:2016-09-05 09:49:13

标签: php json

我正在尝试将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"
}

如何输出type我朋友ben的内容?

3 个答案:

答案 0 :(得分:2)

使用类似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"];
}

答案 1 :(得分:0)

要以数组格式获取解码数据,您需要提供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');

答案 2 :(得分:0)

试试这个,

$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;
    }    
}

DEMO