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

PHP二维数组按数字键分组 生成同键去重值的索引子数组

PHP二维数组按键分组并生成唯一值子数组实现方案

核心需求

  • 对带数字键的二维数组按关联键分组
  • 每个分组下生成存储唯一值的索引子数组
  • 实现MySQL中多行JSON类型字段option_sons的数据合并,最终得到单个键对应多个不同值的数组结构

现有原始数据

当前生成的冗余二维数组结构如下:

Array ( 
    [0] => Array ( [2] => 3 ) 
    [1] => Array ( [3] => 5 ) 
    [2] => Array ( [2] => 4 ) 
    [3] => Array ( [3] => 5 ) 
)

对应MySQL中存储的两行option_sons字段示例值:

{
    "2": "3",
    "3": "5"
}
{
    "2": "4",
    "3": "5"
}

期望输出结构

Array (
    [2] => Array( 3, 4 )
    [3] => Array( 5 )
)

问题原因

原有生成逻辑每次遍历JSON键值对时,都将单组键值对作为独立一维数组压入容器,生成了分散的二维结构,且没有做分组初始化和值去重处理。

实现代码

方案1:优化源头生成逻辑(推荐,性能更高)

直接在遍历数据库查询结果时完成分组和去重,无需生成冗余中间数组:

$optionValuesArrayContainer = array();

foreach ($item_options as $item_options_data) :
    // 解码JSON字段为关联数组,第二个参数true指定返回数组而非对象
    $optionSons = json_decode($item_options_data["option_sons"], true);
    if (!empty($optionSons)) {
        foreach ($optionSons as $item => $value) :
            // 分组键不存在时先初始化空数组
            if (!isset($optionValuesArrayContainer[$item])) {
                $optionValuesArrayContainer[$item] = [];
            }
            // 值未重复时才追加,自动实现去重
            if (!in_array($value, $optionValuesArrayContainer[$item])) {
                $optionValuesArrayContainer[$item][] = $value;
            }
        endforeach;
    }
endforeach;

print_r($optionValuesArrayContainer);

方案2:对已生成的冗余二维数组做二次处理

如果已经拿到了分散的二维数组,可以通过遍历二次组装得到目标结构:

$result = [];
foreach ($optionValuesArrayContainer as $singleItem) {
    // 取每个一维数组的唯一键,PHP7.3+可用array_key_first,低版本替换为key($singleItem)
    $currentKey = array_key_first($singleItem);
    $currentVal = $singleItem[$currentKey];
    
    if (!isset($result[$currentKey])) {
        $result[$currentKey] = [];
    }
    if (!in_array($currentVal, $result[$currentKey])) {
        $result[$currentKey][] = $currentVal;
    }
}

print_r($result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:24:21