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存在!你能幫我重構我的代碼嗎? 謝謝!
是的,正確的,這樣它工程.... $對象[ '型']不存在。 ..它的意思是$ object ['id'],你會知道,因爲你在運行它時會遇到同樣的錯誤。 :) – TimBrownlaw