简体   繁体   中英

How to access child array key value pair in Laravel controller?

My response code :

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

I want to access base_id of of every object in child array 'minicomp' whose parent is 'Shipping'. How can I access it?

First convert your json into array using json_decode() .Like this..

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

Then 

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

Example:

<?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

For getting all ids.Without defining indexes.Use foreach loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM