在ThinkPHP5中,虽然它是一个PHP框架,但处理多维数组以统计某个值的总数仍然是基于PHP原生方法的。如果你想要统计一个多维数组中某个特定值出现的次数,可以使用递归函数来遍历数组。下面是一个示例代码,演示如何实现这一功能:

<?php
use think\Controller;
class ExampleController extends Controller
{
public function countValueInArray($array, $value)
{
$count = 0;
// 定义递归函数来遍历数组
$recursiveFunction = function($subArray) use (&$count, &$recursiveFunction, $value) {
foreach ($subArray as $item) {
if (is_array($item)) {
// 如果当前项是数组,则递归调用
$recursiveFunction($item);
} else {
// 如果当前项等于要统计的值,则计数加一
if ($item === $value) {
$count++;
}
}
}
};
// 开始遍历数组
$recursiveFunction($array);
return $count;
}
public function index()
{
$multiDimensionalArray = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 30],
['nested' => ['name' => 'Diana', 'age' => 28], 'other' => 30]
];
$valueToCount = 30;
$total = $this->countValueInArray($multiDimensionalArray, $valueToCount);
echo "The value {$valueToCount} appears {$total} times in the array.";
}
}

这段代码定义了一个名为ExampleController的控制器,其中包含一个countValueInArray方法,用于递归地遍历多维数组并统计指定值的出现次数。在index方法中,我们创建了一个多维数组作为示例,并调用了countValueInArray方法来统计值30出现的次数,最后输出结果。

如果你想统计多维数组中某个字段值的总和,你可以稍微修改上面的countValueInArray方法,使其计算值的总和而不是计数。这里是一个示例代码:

<?php
use think\Controller;
class ExampleController extends Controller
{
public function sumFieldInArray($array, $field)
{
$sum = 0;
// 定义递归函数来遍历数组
$recursiveFunction = function($subArray) use (&$sum, &$recursiveFunction, $field) {
foreach ($subArray as $key => $item) {
if (is_array($item)) {
// 如果当前项是数组,则递归调用
$recursiveFunction($item);
} elseif (is_numeric($item) && $key === $field) {
// 如果当前项是数字且键匹配要统计的字段,累加到总和
$sum += $item;
}
}
};
// 开始遍历数组
$recursiveFunction($array);
return $sum;
}
public function index()
{
$multiDimensionalArray = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 30],
['nested' => ['name' => 'Diana', 'age' => 28], 'other' => 30]
];
$fieldName = 'age';
$totalSum = $this->sumFieldInArray($multiDimensionalArray, $fieldName);
echo "The total sum of the {$fieldName} field is {$totalSum}.";
}
}

在这个例子中,sumFieldInArray方法会遍历数组,查找与给定字段名相匹配的项,并将这些项的值累加到总和中。在index方法中,我们统计了age字段的总和,并输出结果。

本站无任何商业行为
个人在线分享 » Thinkphp5统计多维数组某个字段的个数和某个字段值相加的方法
E-->