将二维数组中的关联行(带有数字键)分组,以生成每个组中唯一值的索引子数组

问题描述 投票:0回答:2

我有这个数组:

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

我想要的是像这样合并数组:

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

这是生成原始数组的代码:

$optionValuesArrayContainer = array();

foreach($item_options as $item_options_data):
//$item_options_data["option_sons"] is a json object saved in mysql json
    if(count($item_options_data["option_sons"])>0){
        
    foreach(json_decode($item_options_data["option_sons"]) as $item=>$value):
        //$newd[$item] = $value;
        array_push($optionValuesArrayContainer, array($item=>$value));
    endforeach;
}
endforeach;

print_r($optionValuesArrayContainer);

更多说明: 在 mysql 中,我有多行。 这些行中的一列名为“option_sons”,它是一个 json 列,如下所示:

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

另一栏目:

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

我想合并不同行的列以获得一个键但多个不同值的数组。

php arrays multidimensional-array grouping unique
2个回答
2
投票

如果我理解您尝试正确执行的操作,它是根据子数组的键和值合并子数组(如果它们的值相同),因此您需要删除其中之一。 注意:我尝试使用 json 创建一个原始数组来显示真正的答案。我希望它是正确的。

$item_options = [
    ['option_sons' => '{"2":3, "3":5}'],
    ['option_sons' => '{"2":4, "3":5}'],
];

$result = [];
foreach ($item_options as $item_options_data) {
    foreach (json_decode($item_options_data["option_sons"]) as $key => $value) {
        if (!isset($result[$key])) {
            $result[$key] = [];
        }
        
        $result[$key] = array_unique(array_merge($result[$key], [$value]));
    }
}

echo '<pre>';
var_dump($result);

我们有子数组,所以我们需要两个循环,但更重要的是,我们需要像 if 语句一样从键创建结果数组,然后合并子数组并获取唯一值以删除重复值。


0
投票

使用键查找比在嵌套循环内合并和调用

array_unique()
更有效。

为了确保索引元素被推入子数组中,如果确定之前是否遇到过键值对,请使用查找数组。

通过更加小心推入结果数组的内容,就无需在循环期间或循环之后进行清理。

代码:(演示

$array = [
    ['option_sons' => '{"2":3, "3":5}'],
    ['option_sons' => '{"2":4, "3":5}'],
];

$result = [];
foreach ($array as ['option_sons' => $json]) {
    foreach (json_decode($json) as $k => $v) {
        if (!isset($lookup[$k][$v])) {
            $lookup[$k][$v] = $v;
            $result[$k][] = $v;
        }
    }
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.