You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP统计多维数组指定索引相同值数量并生成结果数组

PHP 7.3 多维数组指定索引值频次统计方案

实现思路

遍历原始多维数组,以目标索引位的取值作为统计结果的键,每匹配到一次相同值,对应键的计数加1即可。该逻辑无版本兼容问题,PHP 7.3环境可直接运行。

完整可运行代码

<?php
// 待处理原始多维数组
$rawArray = [
    ['CHICAGO', 14, 'MUFFIN A LINE', 'MUFA-D', 'Arm Bearings - Check for play, lubricate if needed.'],
    ['CHICAGO', 14, 'MUFFIN A LINE', 'MUFA-D', 'Linkage - Check for wear and broken links.'],
    ['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Gear Box oil level'],
    ['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Bearings visual inspection'],
    ['MEMPHIS', '05', 'BREADING LINE 1', 'BRD1-IS', 'Electrical Plug condition'],
    ['CHICAGO', '02', 'JBC LINE 2', 'JBC-BAK-B', 'Plate separator shaft']
];

$targetIndex = 3; // 要统计的目标索引,此处对应需要统计的索引[3]
$countResult = [];

foreach ($rawArray as $item) {
    // 跳过缺失目标索引的异常行,避免运行报错
    if (!isset($item[$targetIndex])) {
        continue;
    }
    $currentVal = $item[$targetIndex];
    $countResult[$currentVal] = isset($countResult[$currentVal]) ? $countResult[$currentVal] + 1 : 1;
}

print_r($countResult);
?>

精简写法

如果确认所有数组行都存在目标索引,无需异常判断,可直接调用内置函数实现,代码更短:

<?php
$targetColumn = array_column($rawArray, 3); // 提取所有行索引为3的值组成一维数组
$countResult = array_count_values($targetColumn); // 直接统计一维数组内值的出现次数
?>

运行结果

两种写法输出的统计结果完全一致:

Array
(
    [MUFA-D] => 2
    [BRD1-IS] => 3
    [JBC-BAK-B] => 1
)

注:描述的预期结果中BRD-IS和原始数组内的实际值BRD1-IS存在字符偏差,对应值的统计次数3次和预期完全匹配,属于笔误。如果需要统计其他索引的频次,直接修改$targetIndex(或array_column的第二个参数)为对应索引值即可。

内容的提问来源于stack exchange,提问作者bbrindza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 03:09:29