2017-07-02 87 views
-5

我有這個數據的JSON:JSON KEY VALUE LOOP PHP

$data = "meta_data":[ 
{ 
    "id":2279, 
    "key":"codice_fiscale", 
    "value":"gege" 
}, 
{ 
    "id":2280, 
    "key":"numero_tessera_titolare", 
    "value":"gre" 
}, 
{ 
    "id":2281, 
    "key":"classe_tessera_titolare", 
    "value":"gre" 
}, 
{ 
    "id":2282, 
    "key":"tratta_da", 
    "value":"gre" 
}, 
{ 
    "id":2283, 
    "key":"tratta_a", 
    "value":"grge" 
}, 
{ 
    "id":2284, 
    "key":"studente", 
    "value":"studente" 
}]; 

我需要循環所有「鑰匙」,當我發現我所需要的密鑰(在這種情況下,「STUDENTE」)我需要獲取存儲在「值」中的值。

我怎樣才能做到這一點在PHP?

編輯

我嘗試這樣做:

foreach($data as $row){ 
    if($row->key=='studente'){ 
     $var = $row->value; 
    } 
} 
+0

[用PHP解析JSON文件(的可能的複製https://stackoverflow.com/questions/4343596/parsing-json -file與 - PHP) – axierjhtjz

回答

0

首先,$數據是不是一個有效的JSON。您可以使用json_decode()來獲取您的json字符串的php數組表示形式。然後遍歷數組。

實施例:

$json = '{ 
"meta_data": [ 
{ 
    "id": 2279, 
    "key": "codice_fiscale", 
    "value": "gege" 
}, 
// other items... 
{ 
    "id": 2283, 
    "key": "tratta_a", 
    "value": "grge" 
}, 
{ 
    "id": 2284, 
    "key": "studente", 
    "value": "studente" 
} 
]}'; 

$data = json_decode($json, true); 
//var_dump($data); 

foreach($data['meta_data'] as $key => $item) { 
    if (isset($item['value']) && $item['value'] == 'studente') { 
     var_dump($item); 
    } 
} 
1

最好/最有效的方式是寫以break foreach循環。

代碼:(Demo

$json = '{ 
"meta_data": [ 
{ 
    "id": 2279, 
    "key": "codice_fiscale", 
    "value": "gege" 
}, 
{ 
    "id": 2283, 
    "key": "tratta_a", 
    "value": "grge" 
}, 
{ 
    "id": 2284, 
    "key": "studente", 
    "value": "studente" 
} 
]}'; 

$data = json_decode($json, true); 
$search='studente'; 

$found=false; 
foreach($data['meta_data'] as $d){ 
    if($d['key']==$search){ 
     $found=$d['value']; 
     break; 
    } 
} 
echo $found?$found:"$search not found"; 

輸出:

studente 
相關問題