简体   繁体   English

PHP 在键和值等于的多维数组中计数值

[英]PHP count values in multidimensional-array where key and value equals

I'm trying to create a dashboard with some information like how many users are male or female.我正在尝试创建一个仪表板,其中包含一些信息,例如有多少用户是男性或女性。 I'm storing profile information already in one multidimensional-array called 'users'.我已经将个人资料信息存储在一个名为“用户”的多维数组中。 To count the total male/female users I want to use a function with multiple arguments (the array, key and value.要计算男性/女性用户总数,我想使用 function 和多个 arguments(数组、键和值。

I tried the following code:我尝试了以下代码:

  <?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,function($element) {
        return $element[$key]== $value;
      }));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
  ?>

This results in Undefined variable: key/values.这导致未定义的变量:键/值。 What am I doing wrong?我究竟做错了什么?

The problem is that anonymous functions in PHP do not have access to variables outside of their own scope.问题是 PHP 中的匿名函数无法访问它们自己的 scope 之外的变量。 As such, the array_filter() callback function you've provided has no knowledge of $key or $value , and so they're undefined variables within that function scope.因此,您提供的array_filter()回调 function 不知道$key$value ,因此它们是 function Z31A1FD140BE4BEF2D11E121EC9A8 中的未定义变量。 To fix this, you must explicitly pass the external variables into the function scope using the use keyword, like function() use ($external_variable) {} .要解决此问题,您必须使用use关键字将外部变量显式传递到 function scope 中,例如function() use ($external_variable) {}

In your case, the solution would look something like this:在您的情况下,解决方案将如下所示:

<?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,function($element) use ($key, $value) {
        return $element[$key]== $value;
      }));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
?>

If you're using PHP 7.4 or above, you can also just use an arrow function to allow the external scope to become part of the function scope implicitly: If you're using PHP 7.4 or above, you can also just use an arrow function to allow the external scope to become part of the function scope implicitly:

<?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,fn($element) => $element[$key]== $value ));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
?>

try尝试

function($element) use ($key, $value) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM