【问题标题】:Count total number of subarrays with certain value where value is a variable计算具有特定值的子数组的总数,其中 value 是一个变量
【发布时间】:2012-10-16 09:41:03
【问题描述】:

我正在尝试使用此问题的答案中的代码:Count values in subarray

但它不想使用变量?

例如,这是可行的:

echo count(array_filter($tasks, function($element){
    return $element['parent'] == 15;
}));

回声:4

但这失败了:

$number = 15;

//Kolla ifall denna har subtasks?
echo count(array_filter($tasks, function($element) {
    return $element['parent'] == $number;
}));

回显 0

有什么想法吗?

【问题讨论】:

  • 同样的问题:“失败”是什么意思?
  • 抱歉,我已经更新了问题

标签: php arrays count


【解决方案1】:

由于$number在lambda函数内部不可用,添加use ($number)

$number = 15;
//Kolla ifall denna har subtasks?
echo count(array_filter($tasks, function($element) use ($number) {
return $element['parent'] == $number;
}));

【讨论】:

  • 您可能还想考虑将变量$number 作为函数参数传递。这使代码更容易理解。
  • 我不认为array_filter() 可以做到这一点,我也不认为这会让事情变得更容易。对于 PHP 5.2,这里有一个丑陋的解决方法:stackoverflow.com/questions/5482989/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
相关资源
最近更新 更多