我正在处理csv,如果三个键中的两个匹配,则需要组合一个数组。例如,采用以下示例:
<?php
$data = [
[
'id' => 1,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 2,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 3,
'player' => 'Mike',
'sport' => 'Soccer'
]
];
以下是所需的结果。
$wanted = [
[
'id' => [1,2],
'player' => 'John',
'sport' => 'Football',
],
[
'id' => [3],
'player' => 'Mike',
'sport' => 'Soccer',
],
];
实现这一目标的最佳方法是什么?
答案 0 :(得分:2)
检查出来
<?php
$data = [
[
'id' => 1,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 2,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 3,
'player' => 'Mike',
'sport' => 'Soccer'
]
];
function combine($input){
$output = [];
foreach($input as $subarray){
$output[$subarray['player']]['id'][] = $subarray['id'];
$output[$subarray['player']]['player'] = $subarray['player'];
$output[$subarray['player']]['sport'] = $subarray['sport'];
}
return array_values($output);
}
print_r(combine($data));
输出
Array
(
[0] => Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[player] => John
[sport] => Football
)
[1] => Array
(
[id] => Array
(
[0] => 3
)
[player] => Mike
[sport] => Soccer
)
)
答案 1 :(得分:1)
检查出来
<?php
$data = [
[
'id' => 1,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 2,
'player' => 'John',
'sport' => 'Football'
],
[
'id' => 3,
'player' => 'John',
'sport' => 'soccer'
],
[
'id' => 4,
'player' => 'John',
'sport' => 'soccer'
],
[
'id' => 5,
'player' => 'Mike',
'sport' => 'Soccer'
]
];
function combine($input){
$output = [];
foreach($input as $subarray){
$output[$subarray['player'].$subarray['sport']]['id'][] = $subarray['id'];
$output[$subarray['player'].$subarray['sport']]['player'] = $subarray['player'];
$output[$subarray['player'].$subarray['sport']]['sport'] = $subarray['sport'];
}
return array_filter(array_values($output));
}
print_r(combine($data));
输出
Array
(
[0] => Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[player] => John
[sport] => Football
)
[1] => Array
(
[id] => Array
(
[0] => 3
[1] => 4
)
[player] => John
[sport] => soccer
)
[2] => Array
(
[id] => Array
(
[0] => 5
)
[player] => Mike
[sport] => Soccer
)
)