Extract [cat_ID] from array PHP - 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
}
}

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.

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'

Related

Create simple array from complex array

I have the following two arrays:
Array One
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 )
[1] => WP_Term Object ( [term_id] => 38 [name] => Geometry [slug] => geometry [term_group] => 0 [term_taxonomy_id] => 38 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 2 [filter] => raw [term_order] => 0 )
)
Array Two
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 ) )
I'm trying to compare the two arrays to find if there are any matches for the [term_id] values as such:
$match = array_intersect($array_one_ids, $array_two_ids);
if( count($match) > 0) { echo 'we have a match!'; }
My question is, how can I create arrays (defined by $array_one_ids and $array_two_ids) of just the term_id values in each of the above arrays such that $array_one_ids would = array(36, 38) and $array_two_ids would = array(36)?
You can use array_column on each of the input arrays to convert them to arrays of term_id.
$match = array_intersect(
array_column($arrayOne, 'term_id'),
array_column($arrayTwo, 'term_id')
);
For older PHP versions where array_column doesn't handle arrays of objects, you can use array_map to extract that property.
$match = array_intersect(
array_map(function($term) { return $term->term_id; }, $arrayOne),
array_map(function($term) { return $term->term_id; }, $arrayTwo)
);
Also, you don't have to count $match to check the result, as an array evaluates to true or false in an if condition depending on whether it's empty. (See "converting to boolean".)
if ($match) { echo 'we have a match!'; }
If you do not need the whole WP_Term object, you can add a fields parameter to your query when you retrieve it to only retrieve the ids of the terms.
For example:
$queryOne = new WP_Term_Query(array(
'taxonomy' => 'emp_unit_name',
... // The other args of your query,
'fields' => 'ids'
));
Then you can access the ids ($query->terms):
array(36, 38);
Once you have both queries, you could do:
$match = array_intersect($queryOne->terms, $queryTwo->terms);
However, if you need the whole object, you can do it like #Don't Panic's answer.

PHP check if value exists in multi-tier array

I have a PHP array, assigned to $terms, from Wordpress that looks like this when printed:
Array ( [0] => WP_Term Object (
[term_id] => 19
[name] => Tshirts
[slug] => tshirts
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => clothes
[description] =>
[parent] => 0
[count] => 6
[filter] => raw
)
[1] => WP_Term Object (
[term_id] => 30
[name] => Pants
[slug] => pants
[term_group] => 0
[term_taxonomy_id] => 30
[taxonomy] => clothes
[description] =>
[parent] => 0
[count] => 12
[filter] => raw
)
)
I am trying to use in_array() to check if a value exists within the array, but I am having trouble since the array contains more parameters than just the categories. Let's say I want to see if pants exists in this array, here's what I've tried:
if (in_array('pants', $terms)) {
echo "Pants in array";
}
How can I modify this if statement so that it checks if pants exists as a slug in this array?
You can use array_search and array_column in combination. You'll want to turn the WP_Term object to an array too. Luckily it has a to_array() method for that so we can use array_map to convert them en masse in our function before searching the items:
var_dump(termsContainsSlug('pants', $terms)); // bool(true)
function termsContainsSlug($slug, $terms) {
$terms = array_map(function($term) { return $term->to_array(); }, $terms);
return array_search($slug, array_column($terms, 'slug')) > 0;
}
First, you should transform each object to an array and then test if there are any 'pants' value in.
foreach($terms as $term) {
if (in_array('pants', (array)$term)) {
echo "Pants in array";
}
}
This should transform WP_Term Object -> array
(array)$term

Display the value from a returned object

I have a variable object which stores the value below.
Array
(
[0] => stdClass Object
(
[term_id] => 1
[name] => Uncategorized
[slug] => uncategorized
[term_group] => 0
[term_taxonomy_id] => 1
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 4
[object_id] => 39
[cat_ID] => 1
[category_count] => 4
[category_description] =>
[cat_name] => Uncategorized
[category_nicename] => uncategorized
[category_parent] => 0
)
)
I now want to display the slug from the list of values. How do i do so?
Assuming that object is stored in an array called $array:
echo $array[0]->slug
You can use print_r($yourObject) to print out the entire object for debugging or if you want to print just that value this would work: echo($yourObject[0]->slug); .
If there are multiple array indices then this:
foreach($yourObject as $object)
{
echo $object->slug;
}
Jonh gave you an exact answer...let me explain it a bit
$obj = your_array;//from where you are using var_dump() to see these values..
and then
echo $obj->slug
you can use the same technique for other terms in your dump, like
echo $obj->name
HTH

reducing/filtering an array

I have an array which I want to filter out certain keys. Let's say $subcats equals this array:
Array
(
[0] => stdClass Object
(
[term_id] => 4
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => category
)
[1] => stdClass Object
(
[term_id] => 5
[term_group] => 0
[term_taxonomy_id] => 5
[taxonomy] => category
)
)
All I want is the term_ids in it's own array.
I've tried foreach and array_values, but I can't seem to wrap my head around it at the moment. Should I be using array_filter?
So the result should be $term_ids = array( 4, 5 );
$termIds = array_map(function($i) { return $i->term_id; }, $subcats);
This syntax requires PHP 5.3+.

PHP count object property occurrences

I have a PHP object like below and all I want to know whats the the easiest way to get a count of objects where the property 'typeId' = 3
Array
(
[0] => ABC Object
(
[id] => 13
[typeId] => 3
[sortOrder] => 0
)
[1] => ABC Object
(
[id] => 12
[typeId] => 2
[sortOrder] => 0
)
[2] => ABC Object
(
[id] => 14
[typeId] => 4
[sortOrder] => 0
)
[3] => ABC Object
(
[id] => 15
[typeId] => 3
[sortOrder] => 0
)
)
A simple foreach counter should do:
$count = 0;
foreach ($array as $object) {
if ($object->typeId == 3) $count++;
}
No need to over complicate things
From my point of view, a much nicer solution is to use the array_filter function:
$newarray = array_filter( $old_array, function($object) { return $object->typeId == 3; } );
(note: inline functions only work since PHP 5.3)
Just create a temporary variable called objectCount or something similar, loop through your array and when you find an object where the typeId equals 3 add 1 to objectCount.

Categories