如何在Laravel控制器中访问子数组键值对?

时间:2017-01-29 05:33:51

标签: php multidimensional-array laravel-5

我的回复代码:

true

我想访问其父级为“Shipping”的子数组'minicomp'中每个对象的base_id。我该如何访问它?

1 个答案:

答案 0 :(得分:1)

首先使用json_decode()将json转换为数组。就像这样..

$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'];

?>

更新

获取所有ID。没有定义索引。使用foreach循环:

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