2017-01-29 81 views
0

我響應代碼:如何在Laravel控制器中訪問子陣列鍵值對?

Shpping : [  
{ 
"id": "1", 
"name": "Dress", 
"deleted_at": null, 
"created_at": null, 
"updated_at": null, 
"minicomp": [ 
    { 
    "id": "1", 
    "cname": "basic", 
    "base_id": 44 
    }, 
    { 
    "id": "2", 
    "cname": "Shirt", 
    "base_id": 177444 
    }, 
    { 
    "id": "3", 
    "cname": "Pants", 
    "base_id": 444 
    } 
    ] 
} 
]; 

我要訪問的子陣列「minicomp」每一個對象,其父母爲「運費」的BASE_ID。我怎樣才能訪問它?

回答

1

首先將您的JSON轉換成使用json_decode()。像這陣..

$json =<your json>; 
$array = json_decode($json,true); 

Then 

echo $array['Shpping '][0]]['minicomp'][0]['id'];//outputs 1 

例子:

<?php 
$json = '[{ 
    "id": "1", 
    "name": "Dress", 
    "deleted_at": null, 
    "created_at": null, 
    "updated_at": null, 
    "minicomp": [{ 
     "id": "1", 
     "cname": "basic", 
     "base_id": 44 
    }, { 
     "id": "2", 
     "cname": "Shirt", 
     "base_id": 177444 
    }, { 
     "id": "3", 
     "cname": "Pants", 
     "base_id": 444 
    }] 
}]'; 
$array = json_decode($json,true); 
//print_r($array); 
$minicomp = $array[0]['minicomp']; 
echo $minicomp[0]['id']; 
echo $minicomp[1]['id']; 

?> 

UPDATE

爲了讓所有ids.Without定義indexes.Use foreach循環:

foreach($minicomp as $key=>$value){ 
echo $minicomp[$key]['id']."<br/>"; 
} 
+0

如果我想回顯所有的值而不傳遞其索引值,我應該怎麼做,即直接執行回聲時它應該取其索引值。 @Hek mat – Mohammed

+0

使用foreach循環。 –

+0

@穆罕默德看到更新的答案。 –

相關問題