我下面有一个数组,它是一个通用名称,但姓氏不同。我想将所有这些名称放入一个数组中,并将姓氏数组放入单个数组中。像下面的一样。
Array
(
[0] => Array
(
[Name] => Rahul
[surname] => M
)
[1] => Array
(
[Name] => Rahul
[surname] => D
)
[2] => Array
(
[Name] => Rahul
[surname] => F
)
)
我希望上面的内容像下面的
Array(
[0] => Array(
[Name] => Rahul
[surname] => Array(
[0] => M
[1] => D
[2] => F
)
)
)
答案 0 :(得分:0)
您可以在主数组上循环并像这样附加它:
<?
$names = [];
$names[0]['Name'] = 'Rahul';
$names[1]['Name'] = 'Rahul';
$names[2]['Name'] = 'Rahul';
$names[0]['surname'] = 'M';
$names[1]['surname'] = 'D';
$names[2]['surname'] = 'F';
$commonNames = [];
if (! empty($names)) {
foreach($names as $name) {
$commonNames[0][$name['Name']][] = $name['surname'];
}
}
echo '<pre>';print_r($commonNames);echo '</pre>';
?>
输出:
Array
(
[0] => Array
(
[Rahul] => Array
(
[0] => M
[1] => D
[2] => F
)
)
)
答案 1 :(得分:0)
您可以这样做
$temp = [];
array_walk($arr, function($item,$key) use(&$temp){
$temp[$item['Name']]['Name'] = $item['Name'];
$temp[$item['Name']]["surname"][] = $item['surname'];
});
$temp = array_values($temp);
print_r($temp);
array_values —返回数组的所有值
array_walk —将用户提供的函数应用于数组的每个成员
Demo。