2013-10-21 81 views
1

讓我真的很快得到這個,這是我的源陣列:現有陣列中創建兒童

Array (
    [0] => Array (
     [1] => Array (
      [id] => 1 
      [category] => Men 
      [items] => Array (
       [0] => Array (
        [id] => 1 
        [name] => Shirt 
        [price] => 21.8 
        ) 
       ) 
      ) 
     ) 
    [1] => Array (
     [1] => Array (
      [id] => 2 
      [category] => Men 
      [items] => Array (
       [0] => Array (
        [id] => 2 
        [name] => Trousers 
        [price] => 10.9 
        ) 
       ) 
      ) 
     ) 
    [2] => Array (
     [1] => Array (
      [id] => 3 
      [category] => Men 
      [items] => Array (
       [0] => Array (
        [id] => 3 
        [name] => Hat 
        [price] => 1.9 
        ) 
       ) 
      ) 
     ) 
    [3] => Array (
     [2] => Array (
      [id] => 4 
      [category] => Women 
      [items] => Array (
       [0] => Array (
        [id] => 4 
        [name] => Bra 
        [price] => 24.5 
        ) 
       ) 
      ) 
     ) 
     . 
     . 
     . 

我想現在實現的是通過類似category這樣的結合items

{ 
    "1": { 
     "id": 1, 
     "category": "Men", 
     "items": [ 
      { 
       "id": 1, 
       "name": "Shirt", 
       "price": "5:52" 
      }, 
      { 
       "id": 2, 
       "name": "Trousers", 
       "price": "3:01" 
      }, 
     ] 
    }, 
    . 
    . 
    . 

我已經嘗試了幾種方法與parentId和東西,但無法繞過它。

任何想法如何得到這個?

回答

3

這裏是第一次嘗試:

$output = array(); 

foreach ($source as $data) { 
    foreach ($data as $categoryId => $item) { 
     if (!isset($output[$categoryId])) { 
      $output[$categoryId] = array(
       'id'  => $categoryId, 
       'category' => $item['category'], 
       'items' => array(), 
      ); 
     } 

     $output[$categoryId]['items'] = array_merge(
      $output[$categoryId]['items'], 
      $item['items'] 
     ); 
    } 
} 

您可能需要以不同方式處理的項目,這取決於有多少項目是在源陣列中的每個元素。我也不太清楚你在預期產出中的價格價值,所以你可能需要詳細說明。

鍵盤:http://codepad.org/tY15P0Qa

+0

謝謝!這一個真的有用。價格值只是虛擬的,不需要擔心:) – AimanB

1

你可以嘗試這樣的事情,在這裏$catalog_item是你最初的陣列和$new_catalog所需陣列:

$new_catalog = array() ; 
    foreach($catalog_item as $grouping) { 
     $mixed_cat_item = array_pop($grouping) ; 
     if(! array_key_exists($mixed_cat_item[ 'id' ], $new_catalog) { 
      $new_catalog[ $mixed_cat_item[ 'id' ] ] = array('id' => $mixed_cat_item[ 'id' ], 'category' => $mixed_cat_item[ 'category' ], 'items' => array()) ; 
     } 
     $item = array_pop($mixed_cat_item[ 'items' ]) ; 
     $new_catalog[ 'id' ][ 'items' ][ ] = $item ; 
    }