PHP搜索数组在数组中

时间:2012-03-28 14:39:34

标签: php

我有这样的数组结果:

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
        )
.
.
.
)

如何搜索多维数组并计算结果数(例如,我想搜索值为4的info_type_id)?

3 个答案:

答案 0 :(得分:10)

使用array_filter过滤数组:

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

echo count(array_filter($yourArray, "test"));

答案 1 :(得分:5)

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);

答案 2 :(得分:1)

你应该试试这个:

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