任何人都可以解释如何使用这个数组:
array(
'Anto' => 25,
'Filip' => 22,
'Marko' => 17,
'Josip' => 23,
'Igor' => 24,
'Ivan' => 23,
);
并将其映射为:
array(
17 => [1, 'Marko'],
22 => [1, 'Filip'],
23 => [2, 'Josip', 'Ivan'],
24 => [1, 'Igor'],
25 => [1, 'Anto'],
);
新数组包含年龄(来自初始数组的值)的键,值是一个数组,其中包含具有相同年龄的人数,后跟所有具有相同年龄的名称。
答案 0 :(得分:1)
foreach
比array_map()
更简单。我还利用array_key_exists()
和ksort()
来使事情更清洁。请参阅下面的文档示例。
<强> 实施例 强>
// Data.
$initialArray = array(
'Anto' => 25,
'Filip' => 22,
'Marko' => 17,
'Josip' => 23,
'Igor' => 24,
'Ivan' => 23,
);
$newArray = array();
// Loop.
foreach($initialArray as $name => $age) {
if(!array_key_exists($age, $newArray)) {
// Initialize this age in the new array with empty counter.
$newArray[$age] = array(0);
}
// Increment the counter.
$newArray[$age][0]++;
// Append the name.
$newArray[$age][] = $name;
}
// Sort by age.
ksort($newArray);
// Dump.
print_r($newArray);
<强> 输出: 强>
Array
(
[17] => Array
(
[0] => 1
[1] => Marko
)
[22] => Array
(
[0] => 1
[1] => Filip
)
[23] => Array
(
[0] => 2
[1] => Josip
[2] => Ivan
)
[24] => Array
(
[0] => 1
[1] => Igor
)
[25] => Array
(
[0] => 1
[1] => Anto
)
)
这只是众多方法之一。我强烈建议您更多地了解foreach
控件结构,以便您完全掌握这个概念......作为程序员,它必须向前发展!
您也可以通过在逻辑结尾添加计数器来完成此操作。首先,您将根据其年龄对每个名称进行排序。然后,您将在count($names)
索引处将$names
添加到$age
数组的开头。
答案 1 :(得分:0)
您可以使用array_walk
。你走了:
$array = [
'John' => 25,
'Tony' => 25,
'Anto' => 25,
'Filip' => 22,
'Marko' => 17,
'Josip' => 23,
'Igor' => 24,
'Ivan' => 23,
];
$ages = [];
array_walk($array, function ($age, $name) use (&$ages) {
// Does the age already exist? If so, we'll increment
// the count, otherwise we'll initialize it to one.
array_key_exists($age, $ages) ? $ages[$age][0]++ : $ages[$age][0] = 1;
$ages[$age][] = $name;
});
var_dump($ages);
输出:
array:5 [▼
25 => array:4 [▼
0 => 3
1 => "John"
2 => "Tony"
3 => "Anto"
]
22 => array:2 [▼
0 => 1
1 => "Filip"
]
17 => array:2 [▼
0 => 1
1 => "Marko"
]
23 => array:3 [▼
0 => 2
1 => "Josip"
2 => "Ivan"
]
24 => array:2 [▼
0 => 1
1 => "Igor"
]
]