我有下一个结构的数组:
$collection = array (
array('category' => 'buildings',
'id' => 9),
array('category' => 'buildings',
'id' => 8),
array('category' => 'trees',
'id' => 11),
array('category' => 'trees',
'id' => 12),
array('category' => 'trees',
'id' => 11),
)
我需要创建下一个集合:
array ('buildings' => array (9, 8),
'trees' => array (10, 12, 11),
)
所以我用它来foreach()和array_push()。首先,如果新集合不是当前类别。如果没有,我设置空数组,将id推送到它。但是如果类别存在于新集合中,我将id值推送到数组ans添加到集合中。所以我的代码是:
function getCategoriesAndTypes($collection)
{
$categoriesAndTypes = [];
$typesCollection = [];
foreach ($collection as $object) {
$category = $object['category'];
if (! array_key_exists($category, $categoriesAndTypes)) {
$typesCollection = [];
array_push($typesCollection, $object['type']);
$categoriesAndTypes[$category] = $typesCollection;
} else {
array_push($typesCollection, $object['type']);
$categoriesAndTypes[$category] = $typesCollection;
}
}
return $categoriesAndTypes;
}
但我认为存在更多漂亮的解决方案!你能帮我重构我的代码吗? 谢谢!
答案 0 :(得分:0)
我已将我的代码重构为下一个版本:
function getCategoriesAndTypesFromLibraryFolder($collection)
{
$categoriesAndTypes = [];
$typesCollection = [];
foreach ($collection as $object) {
if (! array_key_exists($object['category'], $categoriesAndTypes)) {
$typesCollection = [];
}
array_push($typesCollection, $object['type']);
$categoriesAndTypes[$object['category']] = $typesCollection;
}
return $categoriesAndTypes;
}
你有没有想过让它变得更好?
答案 1 :(得分:0)
以下方法就足够了:
function getCategoriesAndTypesFromLibraryFolder($collection)
{
$categoriesAndTypes = [];
foreach ($collection as $item) {
$categoriesAndTypes[$item['category']][] = $item['id'];
}
return $categoriesAndTypes;
}
结果是:
array ( 'buildings' => array ( 0 => 9, 1 => 8, ),
'trees' => array ( 0 => 11, 1 => 12, 2 => 11, ), )