在数组内的数组中获取特定实体的计数?

时间:2016-12-13 09:15:55

标签: php arrays count

我有一个名为hello的数组,如下所示,

hello(
    0 => ([name => abc, add=>def, city=>ny,phone=>12345]);
    1 => ([name => pqr, add=>mno, city=>qw,phone=>67890]);
    2 => ([name => abc, add=>def, city=>ny,phone=>14785]);
    3 => ([name => ghi, add=>foo, city=>yu,phone=>258]);
    4 => ([name => jkl, add=>exy, city=>ny,phone=>95145]);
);

它具有很少的元素,并且元素也是数组本身,就像在查询结果时一样。 我想算一个重复的特定名称。就像在hello [0]和hello [2]中一样,我的ans应该是abc = 2.

我该怎么做?

感谢。

3 个答案:

答案 0 :(得分:0)

编辑2: 现在你想要一种计算所有对象的方法:

$arr = [
    0 => (object) ['name' => 'abc', 'add'=>'def', 'city'=>'ny', 'phone'=>'12345'],
    1 => (object) ['name' => 'pqr', 'add'=>'mno', 'city'=>'qw', 'phone'=>'67890'],
    2 => (object) ['name' => 'abc', 'add'=>'def', 'city'=>'ny', 'phone'=>'14785'],
    3 => (object) ['name' => 'ghi', 'add'=>'foo', 'city'=>'yu', 'phone'=>'258'],
    4 => (object) ['name' => 'jkl', 'add'=>'exy', 'city'=>'ny', 'phone'=>'95145'],
];

function countBy (callable $f, $xs) {
  return array_reduce($xs, function ($acc, $x) use ($f) {
    $y = call_user_func($f, $x);
    $acc[$y] = isset($acc[$y]) ? $acc[$y] + 1 : 1;
    return $acc;
  }, []);
}

json_encode(countBy (function ($x) { return $x->name; }, $arr));
// => { "abc": 2, "pqr": 1, "ghi": 1, "jkl": 1 } 

修改 您对数据类型撒谎,因此我将$x['name']更改为$x->name并将$x[$attr]更改为$x->{$name}

您可以使用array_reduce

array_reduce($arr, function ($acc, $x) {
  return $x->name === 'abc' ? $acc + 1 : $acc;
}, 0);
// => 2

或将其写为函数

function countAttr($attr, $match, $xs) {
  return array_reduce($xs, function ($acc, $x) use ($attr, $match) {
    return $x->{$attr} === $match ? $acc + 1 : $acc;
  }, 0);
}

countAttr('name', 'abc', $arr)(
// => 2

答案 1 :(得分:0)

在这种情况下,定义function最好,以便获得任何名称的计数。你可以试试这个 -

$array = [
    0 => ['name' => 'abc', 'add'=>'def', 'city'=>'ny','phone'=>'12345'],
    1 => ['name' => 'pqr', 'add'=>'mno', 'city'=>'qw','phone'=>'67890'],
    2 => ['name' => 'abc', 'add'=>'def', 'city'=>'ny','phone'=>'14785'],
    3 => ['name' => 'ghi', 'add'=>'foo', 'city'=>'yu','phone'=>'258'],
    4 => ['name' => 'jkl', 'add'=>'exy', 'city'=>'ny','phone'=>'95145'],
];
function get_name_count($array, $name)
{  
    // filter array for name
    $temp = array_filter($array, function($a) use($name) {
        return ($a['name'] === $name);
    });
    // return count
    return count($temp);
}

var_dump(get_name_count($array, 'abc'));

<强>输出

int(2)

答案 2 :(得分:-1)

// hello , please use some standard name for array 
// code not tested 
// define variable if required 
$field_name="name";
$value="abc";
$count=0;
echo count_field($field_name,$value);
function count_field($field_name,$value)
{
 foreach($hello as $val)
 {
   if($val[$field_name]==$value)
   {
   $count++;
   }
 }
 return $count;
}