4

I have the following array (just a part of the complete array) and I want to extract the value of [cat_ID].

Array ([1] => stdClass Object ( [term_id] => 21 [name] => z_aflyst [slug] => z_aflyst
[term_group] => 0 [term_taxonomy_id] => 23 [taxonomy] => category 
[description] => [parent] => 0 [count] => 1 [object_id] => 7 [cat_ID] => 21 
[cat_name] => z_aflyst ))

So I need to extract the 21 in this case. However, I only want to extract the cat_ID if the cat_name equals z_aflyst.

Rvervuurt
  • 7,171
  • 7
  • 35
  • 53

3 Answers3

1

Give that you have an array of objects:

Array (
[1] => stdClass Object 
( 
[term_id] => 21 
[name] => z_aflyst 
[slug] => z_aflyst
[term_group] => 0 
[term_taxonomy_id] => 23 
[taxonomy] => category 
[description] => 
[parent] => 0 
[count] => 1 
[object_id] => 7 
[cat_ID] => 21 
[cat_name] => z_aflyst )
)

foreach ($items as $item)
{
    if($item->cat_name == 'z_aflyst')
    {
        //do stuff
    }
}
ka_lin
  • 8,596
  • 5
  • 31
  • 50
0

Your array is in this example a little more than a simple array, is a standard object. And you can take advantage of this. You can the properties of a standard object by this formula:

$object->property;

in your case the object is

$object = $array[1];

or by this formula as an array

$array[key];

in your case to get the value of cat_ID:

$object->cat_ID;

So your code will be something like:

if ($object->cat_name == 'z_aflyst') {
     // do stuff with your cat_ID value
     echo $object->cat_ID;
}
// will echo 21 only of the cat_name has value 'z_aflyst'
Community
  • 1
  • 1
Elzo Valugi
  • 24,234
  • 13
  • 88
  • 112
0

You have an array of standard objects, which properties can be accessed using the arrow (object) operator ->.

You can use array_filter() to filter out unwanted elements of the array:

// Assuming your array is called $items
$filtered = array_filter($items, function($v) {
    return $v->cat_name === 'z_aflyst';
});

After that, you can "flatten" the array using array_map() so that it only contains the cat_ID if you wish:

$filtered = array_map(function($v) {
    return $v->cat_ID;
}, $filtered);

This will leave you with a one-dimension, indexed array of cat_IDs.

rink.attendant.6
  • 36,468
  • 57
  • 89
  • 143