为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁星coding 2021-12-03 15:26:03
这是我从函数中得到的数组结果。我想从数组中获取 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 itforeach ($arr as $obj => $arr) {            foreach ($arr as $obj => $arr) {                print_r($arr->category_id);            }        }
查看完整描述

2 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您实际上不需要在这里嵌套循环,因为第一级不是数组,而是对象。


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

}


查看完整回答
反对 回复 2021-12-03
?
jeck猫

TA贡献1909条经验 获得超7个赞

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


查看完整回答
反对 回复 2021-12-03
  • 2 回答
  • 0 关注
  • 225 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信