1

This is the array result that I get from a function. I want to get the category_id from the array and only echo it.

{"categories": [{"parent_id": 15397, "has_children": true, "category_id": 15402, "category_name": "AC"}, {"parent_id": 0, "has_children": true, "category_id": 15397, "category_name": "A"}], "request_id": "3beac0674e937d2471e4b66b5f998976"}

after I json_decode my result, it shows like this.

stdClass Object ( [categories] => Array ( [0] => stdClass Object ( [parent_id] => 0 [has_children] => 1 [category_id] => 16 [category_name] => Women's Clothing ) [1] => stdClass Object ( [parent_id] => 16 [has_children] => 1 [category_id] => 1585 [category_name] => Dresses )

How to access the category_id when there is 2 stdclass object

//solved it
foreach ($arr as $obj => $arr) {
            foreach ($arr as $obj => $arr) {
                print_r($arr->category_id);

            }

        }
Tinagaran
  • 39
  • 8

2 Answers2

1

You don't actually need to have nested loop here because the first level is not array, but object.

$data = "{"categories": [{"parent_id": 15397, "has_children": true, "category_id": 15402, "category_name": "AC"}, {"parent_id": 0, "has_children": true, "category_id": 15397, "category_name": "A"}], "request_id": "3beac0674e937d2471e4b66b5f998976"}";

// Change to Array
$obj = json_decode($data, true);

// Get the data
foreach($obj['categories'] as $category) {
    print_r($category['category_id']);
}
Adlan Arif Zakaria
  • 1,706
  • 1
  • 8
  • 13
0
<?php
 // Use this function to get the desired result, and then you can pass the result to another function
$data = '{"categories": [{"parent_id": 15397, "has_children": true, "category_id": 15402, "category_name": "AC"}, {"parent_id": 0, "has_children": true, "category_id": 15397, "category_name": "A"}], "request_id": "3beac0674e937d2471e4b66b5f998976"}';

function getCategoreIds($data=[]){
    $cids=[];
    $datas = json_decode($data,true);
    if($datas['categories']){
        foreach($datas['categories'] as $k=>$tmp){
            if(isset($tmp['category_id'])){
                $cids[] = $tmp['category_id'];
            }
        }
    }
    return $cids;
}

print_r(getCategoreIds($data));
shiwei.du
  • 25
  • 2