按两列对二维数组数据进行分层分组,并在每个唯一路径中连接第三列值

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

我需要将二维数组中的数据分组为关联数组的关联数组,其中

d
值是第一级键,
s
值将成为第二级键,
i
值应该是(可能以逗号分隔)各自组中的第二级值。

输入:

$array = [
    ["d" => "7 Apr 2024", "s" => "pm", "i" => "el"],
    ["d" => "8 Apr 2024", "s" => "am", "i" => "mn"],
    ["d" => "12 Apr 2024", "s" => "pm", "i" => "mr"],
    ["d" => "12 Apr 2024", "s" => "am", "i" => "mr"],
    ["d" => "12 Apr 2024", "s" => "am", "i" => "da"],
    ["d" => "13 Apr 2024", "s" => "pm", "i" => "li"],
    ["d" => "14 Apr 2024", "s" => "am", "i" => "li"],
    ["d" => "15 Apr 2024", "s" => "mid", "i" => "nd"],
    ["d" => "15 Apr 2024", "s" => "pm", "i" => "da"]
]

想要的结果:

[
    "7 Apr 2024" => ["pm" => "el"],
    "8 Apr 2024" => ["am" => "mn"],
    "12 Apr 2024" => ["am" => "mr,da", "pm" => "mr"],
    "13 Apr 2024" => ["pm" => "li"],
    "14 Apr 2024" => ["am" => "li"],
    "15 Apr 2024" => ["pm" => "da", "mid" => "nd"]
]

我已经尝试了使用 if 语句、使用 while 语句和临时数组的每个 foreach 循环的每个版本。当日期相同时,我很难组合第二级值。

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

您需要在输入数组上使用 array_walk 来创建输出。

$input = [
[
    "d" => "7 Apr 2024",
    "s" => "pm",
    "i" => "el"
],
[
    "d" => "8 Apr 2024",
    "s" => "am",
    "i" => "mn"
],
[
    "d" => "12 Apr 2024",
    "s" => "pm",
    "i" => "mr"
],
[
    "d" => "12 Apr 2024",
    "s" => "am",
    "i" => "mr"
],
[
    "d" => "12 Apr 2024",
    "s" => "am",
    "i" => "da"
],


[
    "d" => "13 Apr 2024",
    "s" => "pm",
    "i" => "li"
],
[
    "d" => "14 Apr 2024",
    "s" => "am",
    "i" => "li"
],



[
    "d" => "15 Apr 2024",
    "s" => "am",
    "i" => "mr"
],
[
    "d" => "15 Apr 2024",
    "s" => "am",
    "i" => "da"
]
];

$output = [];

array_walk($input, function ($item) use (&$output) {
if (array_key_exists($item["d"], $output) && array_key_exists($item["s"],$output[$item["d"]])) {
    $output[$item["d"]][$item["s"]] .= "," . $item["i"];
} else {
    $output[$item["d"]][$item["s"]] = $item["i"];
}
});

print_r($output);

0
投票

使用两个分组列作为数组的第一层和第二层。如果前两个值的组合未在结果数组中表示,则保存它,否则附加一个逗号和新值。

代码:(演示

foreach ($array as ['d' => $d, 's' => $s, 'i' => $i]) {
    if (!isset($result[$d][$s])) {
        $result[$d][$s] = $i;
    } else {
        $result[$d][$s] .= ',' . $i;
    }
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.