2017-10-22 119 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,),)