我有以下数组:
Array
(
[0] => Array
(
[0] => 2000
[1] => 401
)
[1] => Array
(
[0] => 2000
[1] => 317
)
[2] => Array
(
[0] => 2000
[1] => 301
)
[3] => Array
(
[0] => 2002
[1] => 285
)
[4] => Array
(
[0] => 2002
[1] => 277
)
[5] => Array
(
[0] => 2002
[1] => 271
)
[6] => Array
(
[0] => 2001
[1] => 208
)
[7] => Array
(
[0] => 2001
[1] => 263
)
[8] => Array
(
[0] => 2001
[1] => 262
)
[9] => Array
(
[0] => 2000
[1] => 258
)
)
然后我编写了以下代码来对其值进行分组:
$result06 = array();
foreach ($chart06 as $el) {
if (!array_key_exists($el[0], $result06)) {
$result06[$el[0]] = array();
}
$result06[$el[0]][] = $el[1];
}
我们收到以下结果:
Array
(
[2000] => Array
(
[0] => 401
[1] => 317
[2] => 301
[3] => 258
)
[2002] => Array
(
[0] => 285
[1] => 277
[2] => 271
)
[2001] => Array
(
[0] => 208
[1] => 263
[2] => 262
)
)
现在我如何提取每个子阵列的最大值并将其转换为" flat"数组如下所示?
Array
(
[2000] => 401
[2002] => 285
[2001] => 263
)
我试过了:
foreach ($result06 as $value){
$resultMax[] = max($value);
}
但结果是:
Array
(
[0] => 401
[1] => 285
[2] => 263
)
但我真的需要原始键是一样的。
我将不胜感激任何帮助!
答案 0 :(得分:0)
您可以在foreach
循环中获取密钥,如下所示:
foreach ($result06 as $key => $value){
$resultMax[$key] = max($value);
}
答案 1 :(得分:0)
跳过创建分组数组的中间步骤:
$result06 = array();
foreach ($chart06 as $el) {
if (!isset($result06[$el[0]])) {
$result06[$el[0]] = 0;
}
$result06[$el[0]] += el[1];
}
答案 2 :(得分:0)
仅在第一个位置插入最大值:
foreach ($chart06 as $el) {
if (!array_key_exists($el[0], $result06)) {
$result06[$el[0]] = $el1;
} else {
$result06[$el[0]] = max($result06[$el[0]], $el[1]);
}
}
答案 3 :(得分:0)
我同意AbraCadaver,您绝对可以省去通过标识符对值进行分组的中间步骤。
您只需要迭代原始输入数组并确定:
代码:(Demo)
$array = [
[2000, 401],
[2000, 317],
[2000, 301],
[2002, 285],
[2002, 277],
[2002, 271],
[2001, 208],
[2001, 263],
[2002, 285],
[2001, 262],
[2000, 258]
];
foreach ($array as $row) {
$id = $row[0]; // just to improve readability
if (!isset($result[$id]) || $result[$id] < $row[1]) { // first occurrence or less than current
$result[$id] = $row[1]; // store the current value
}
}
var_export($result);
输出:
array (
2000 => 401,
2002 => 285,
2001 => 263,
)