Extract [cat_ID] from PHP array

I have the following array (only part of the full array) and I want to extract the value [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 21 in this case. However, I want to extract cat_IDif cat_nameequal z_aflyst.

+4
source share
3 answers

Indicate 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
    }
}
+1
source

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

$object->property;

in your case an object

$object = $array[1];

or according to this formula as an array

$array[key];

in your case, to get the cat_ID value:

$object->cat_ID;

, :

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'
0

, () ->.

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

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

After that, you can “smooth out” the array using array_map()so that it contains only cat_ID:

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

This will leave you with a one-dimensional indexed cat_ID array.

0
source

Source: https://habr.com/ru/post/1539551/


All Articles