2017-10-22 130 views
0

我与一个结构数组:创建基于另一个阵列新数组

$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值推送到数组并添加到集合中。所以我的代码是:

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; 
} 

但我认为,更漂亮sollutions存在!你能帮我重构我的代码吗? 谢谢!

回答

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; 
} 

有你的想法,使其更好?

+0

是的,正确的,这样它工程.... $对象[ '型']不存在。 ..它的意思是$ object ['id'],你会知道,因为你在运行它时会遇到同样的错误。 :) – TimBrownlaw

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,),)