我正在尝试创建一个函数,我可以在其中传递一个数组的记录集,然后它将排列一个国家/地区的所有制造商并返回重做数组
我的记录集是
[0] => Array
(
[Cars] => Array
(
[Manufecturer] => Honda
[MID] => 584
)
[Chracterstics] => Array
(
[Country] => Japan
)
)
[1] => Array
(
[Cars] => Array
(
[Manufecturer] => Toyota
[MID] => 531
)
[Chracterstics] => Array
(
[Country] => Japan
)
)
[2] => Array
(
[Cars] => Array
(
[Manufacturer] => KIA
[MID] => 532
)
[Chracterstics] => Array
(
[Country] => Korea
)
)
[3] => Array
(
[Cars] => Array
(
[Manufacturer] => BMW
[MID] => 534
)
[Chracterstics] => Array
(
[Country] => Germany
)
)
[4] => Array
(
[Cars] => Array
(
[Manufacturer] => Mercedece
[MID] => 543
)
[Chracterstics] => Array
(
[Country] => Germany
)
)
[5] => Array
(
[Cars] => Array
(
[Manufacturer] => SAAB
[MID] => 523
)
[Chracterstics] => Array
(
[Country] => Sweden
)
)
在理想的情况下,我会得到一个阵列。
修改 例如
[Japan] => Array
(
[0] => Array(
[Manufacturer] => Honda
)
[1] => Array(
[Manufacturer] => Toyota
)
)
[Sweden] => Array
(
[0] => Array(
[Manufacturer] => SAAB
)
)
感谢
答案 0 :(得分:1)
这可能有用。显然它非常简单,不处理重复,并假设您正在寻找制造商名称而不是ID,但我会留给您,除非您想要更新您的要求。
function getManufacturerByCountry($array) {
$results = array();
foreach ($array as $tmp) {
$results[$tmp['Chracterstics']['Country']][] = $tmp['Cars']['Manufacturer'];
}
return $results;
}
<强>更新强> 为防止重复,
foreach ($array as $tmp) {
$country = $tmp['Chracterstics']['Country'];
$manufacturer = $tmp['Cars']['Manufacturer'];
// Only add manufacturer if new country or if manufacturer isn't in country array.
if (!isset($results[$country]) || !in_array($manufacturer, $results[$country])) {
$results[$country][] = $manufacturer;
}
}