根据php中的键对数组值进行分组?
我有一个这样的数组:
$str=
Array
(
[No] => 101
[Paper_id] => WE3P-1
[Title] => "a1"
[Author] => ABC
[Aff_list] => "University of South Florida, Tampa, United States"
[Abstracts] => "SLA"
)
Array
(
[No] => 101
[Paper_id] => WE3P-1
[Title] => "a2"
[Author] => DEF
[Aff_list] => "University of South Florida, Tampa, United States"
[Abstracts] => "SLA "
)
Array
(
[No] => 104
[Paper_id] => TU5A-3
[Title] => "a3"
[Author] => GHI
[Aff_list] => "University of Alcala, Alcala de Henares, Spain"
[Abstracts] => "Microwave"
)
我想根据“No”作为主键对数组中的元素进行分组。输出应如下所示:
array(6) {
["No"]=>
string(6) "101"
["Paper_id"]=>
string(6) "WE3P-1"
["Title"]=>
string(80) ""a-1"
["Author"]=>
string(14) "ABC"
["Aff_list"]=>
string(51) ""University of South Florida, Tampa, United States""
["Abstracts"]=>
string(5) ""(SLA)"
"
}
array(6) {
["No"]=>
string(3) "104"
["Paper_id"]=>
string(6) "TU5A-3"
["Title"]=>
string(40) "a2"
["Author"]=>
string(20) "DEF"
["Aff_list"]=>
string(48) ""University of Alcala, Alcala de Henares, Spain""
["Abstracts"]=>
string(9) ""Microwave"
"
}
请注意,作者的值已与主键“否”合并。任何人都可以帮我解决这个问题吗?
我尝试这样做:
foreach($paper_info as $element) {
foreach($element as $v) {
$id = $element['No'];
if (!isset($out[$id])) {
$out[$id] = [
'No' => $element['No'],
'Paper_id' => $element['Paper_id'],
'Title' => $element['Title'],
'Authors' => [],
'Aff_list' => $element['Aff_list'],
'Abstracts' => $element['Abstracts']
];
}
$out[$id]['Authors'][] = ['Authors' => $element['Author']];
}
}