2016-09-05 134 views
2

我想解碼JSON數據到PHP然後輸出到網站。如果我有以下幾點: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是什麼?

+0

我們鼓勵你使用'jq'那最適合這種工作。你可能想在類似的問題上檢查我的[\ [other answer \]](http://stackoverflow.com/a/39233446/1620779)。 – sjsam

回答

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"]; 
} 
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'); 
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