I have array result like this:
Array
(
[0] => stdClass Object
(
[id_global_info] => 78
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:54
[date_expires] => 2012-04-14 16:11:54
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[1] => stdClass Object
(
[id_global_info] => 79
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[2] => stdClass Object
(
[id_global_info] => 80
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
.
.
.
)
How can I search a multidimensional array and count number of results (for example I want to search for info_type_id with value of 4)?
You can use array_intersect() .
The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned. Syntax: array_search($value, $array, strict_parameter)
Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
Use array_filter
to filter the array:
function test($arr) {
return $arr["info_type_id"] == 4;
}
echo count(array_filter($yourArray, "test"));
with foreach
?
function searchMyCoolArray($arrays, $key, $search) {
$count = 0;
foreach($arrays as $object) {
if(is_object($object)) {
$object = get_object_vars($object);
}
if(array_key_exists($key, $object) && $object[$key] == $search) $count++;
}
return $count;
}
echo searchMyCoolArray($input, 'info_type_id', 4);
You should try this :
$counter = 0;
$yourArray; // this var is your current array
foreach($yourArray as $object){
if($object->info_type_id == 4){
$counter++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With