如何从PHP中的数组中获取值?

这是我从函数中得到的数组结果。我想从数组中获取 category_id 并且只回显它。


{"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"}

在我 json_decode 我的结果之后,它显示如下。


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 )

有2个stdclass对象时如何访问category_id


//solved it

foreach ($arr as $obj => $arr) {

            foreach ($arr as $obj => $arr) {

                print_r($arr->category_id);


            }


        }


繁星coding
浏览 226回答 2
2回答

慕姐4208626

您实际上不需要在这里嵌套循环,因为第一级不是数组,而是对象。$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 dataforeach($obj['categories'] as $category) {    print_r($category['category_id']);}

jeck猫

<?php&nbsp;// 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=[]){&nbsp; &nbsp; $cids=[];&nbsp; &nbsp; $datas = json_decode($data,true);&nbsp; &nbsp; if($datas['categories']){&nbsp; &nbsp; &nbsp; &nbsp; foreach($datas['categories'] as $k=>$tmp){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(isset($tmp['category_id'])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $cids[] = $tmp['category_id'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $cids;}print_r(getCategoreIds($data));
打开App,查看更多内容
随时随地看视频慕课网APP