PHP search array in array

I get an array as follows:

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 to search for a multidimensional array and count the number of results (for example, I want to look for info_type_id with a value of 4)?

+5
source share
3 answers

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);
+5
source

Use array_filterto filter an array:

function test($arr) { 
    return $arr["info_type_id"] == 4; 
}

echo count(array_filter($yourArray, "test"));
+10
source

You should try the following:

   $counter = 0;
    $yourArray; // this var is your current array
    foreach($yourArray as $object){
          if($object->info_type_id == 4){
                $counter++;
          }
    }
+1
source

All Articles