我有一个像这样的数组,数据来自对象
Array (
'2018' => Array(
'Essence' => 103, // max of all value of the key each 'Essence' key on 2019
'Lalo' => 69 //..
),
// Data from 2015
'2015' => Array(
'Essence' => 97,
'Lalo' => 64, //..
'Mika' => 17, //..
'Sahafa' => 65
'Simba' => 70 //..
)
);
所有,我想创建另一个分组密钥并设置同一年发现的每个密钥的最大值。作为数组的键
{{1}}
答案 0 :(得分:2)
以以下代码开头:
$new_array = [];
foreach ($array as $item) {
$year = $item['year'];
if (!isset($new_array[$year])) {
$new_array[$year] = [];
}
foreach ($item['data'] as $key => $value) {
$new_array[$year][$key] = max($value);
}
}
答案 1 :(得分:2)
这应该有效-
$new = [];
foreach ($arr as $a) {
foreach ($a['data'] as $key => $value) {
// extract max value & set to keys accordingly
$new[$a['year']][$key] = max($value);
}
}
输出
array(2) {
[2018]=>
array(2) {
["Essence"]=>
int(103)
["Lalo"]=>
int(69)
}
[2015]=>
array(5) {
["Essence"]=>
int(97)
["Lalo"]=>
int(97)
["Sahafa"]=>
int(97)
["Mika"]=>
int(17)
["Simba"]=>
int(70)
}
}
答案 2 :(得分:2)
您必须多次应用max
:一次是从最内层序列中获取最大值,然后一次是在与它们相同年份和类型的最大值中获取最大值。
假设输入位于$data
中,则:
foreach ($data as $item) {
foreach($item["data"] as $type => $series) {
$result[$item["year"]][$type] = isset($result[$item["year"]][$type])
? max($result[$item["year"]][$type], max($series))
: max($series);
}
}