简体   繁体   中英

get stdclass object array cat_id value?

How to get cat_id ?

Array
    (
        [0] => stdClass Object
            (
                [id] => 17
                [res_id] => 10
                [cat_id] => 3
            )

        [1] => stdClass Object
            (
                [id] => 18
                [res_id] => 10
                [cat_id] => 4
            )

        [2] => stdClass Object
            (
                [id] => 52
                [res_id] => 19
                [cat_id] => 1
            )

        [3] => stdClass Object
            (
                [id] => 53
                [res_id] => 19
                [cat_id] => 3
            )

        [4] => stdClass Object
            (
                [id] => 54
                [res_id] => 19
                [cat_id] => 4
            )

I want cat_id from all stdClass Object array.

how can i get this ?

Can anyone help me how do I retrieve the value of cat_id? Thanks.

Try this

$Your_array
foreach($Your_array AS $Cat){
   echo $Cat->cat_id;
}
$array = array();
$object = new stdClass;
$object->id= "ID";
$object->res_id = "RES_ID";
$object->cat_id = "CAT_ID";
$array[] = $object;

To Access to object attribute:

echo $array[0]->cat_id;

You can replace 0 with index and iterate it in array:

for($index=0;$index<count($array);$index++){
    if(isset($array[$index]->cat_id)){
        // Do something...
    }
}

Object properties in PHP are accessed using the -> syntax. To get the cat_id property of each item in the array, you could loop through the array to get each item one by one, and store the cat_id property of the objects in a new array, like so:

$cat_ids = array();
foreach($array as $item){
    $cat_ids[] = $item->cat_id;
}

print_r($cat_ids);

Gives:

Array
(
    [0] => 3
    [1] => 4
    [2] => 1
    [3] => 3
    [4] => 4
)

If you don't need all the cat_ids, but just the one for a specific object in your original array, you can use

$array[2]->cat_id;

Which would get the cat_id property of the 3rd item in your array.

You can use array_map . For example, if your source array is $array :

$result = array_map(function($x){
    return $x->cat_id;
}, $array);

print_r($result);

That will give you:

Array
(
    [0] => 3
    [1] => 4
    [2] => 1
    [3] => 3
    [4] => 4
)

Demo

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