简体   繁体   中英

Extract [cat_ID] from array PHP

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 .

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

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'

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.

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