![](/img/trans.png)
[英]Remove lines with empty values from multidimensional-array in php
[英]PHP count values in multidimensional-array where key and value equals
我正在嘗試創建一個儀表板,其中包含一些信息,例如有多少用戶是男性或女性。 我已經將個人資料信息存儲在一個名為“用戶”的多維數組中。 要計算男性/女性用戶總數,我想使用 function 和多個 arguments(數組、鍵和值。
我嘗試了以下代碼:
<?
function countArray($array, $key, $value) {
$cnt = count(array_filter($array,function($element) {
return $element[$key]== $value;
}));
echo $cnt;
}
countArray($users, 'gender', '1');
?>
這導致未定義的變量:鍵/值。 我究竟做錯了什么?
問題是 PHP 中的匿名函數無法訪問它們自己的 scope 之外的變量。 因此,您提供的array_filter()
回調 function 不知道$key
或$value
,因此它們是 function Z31A1FD140BE4BEF2D11E121EC9A8 中的未定義變量。 要解決此問題,您必須使用use
關鍵字將外部變量顯式傳遞到 function scope 中,例如function() use ($external_variable) {}
。
在您的情況下,解決方案將如下所示:
<?
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:
<?
function countArray($array, $key, $value) {
$cnt = count(array_filter($array,fn($element) => $element[$key]== $value ));
echo $cnt;
}
countArray($users, 'gender', '1');
?>
嘗試
function($element) use ($key, $value) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.