2013-02-20 251 views
1

我有一個網站在PHP中開發,我有一個函數,我想在其他數組內創建一個數組。 我的查詢是這樣的(我使用cakephp,但在這種情況下只是一個數組問題,不要告訴我使用包含或類似的東西從cakephp,因爲是一個大的查詢,我需要構造我的查詢和我的數組在這種模式下)推陣列在另一個陣列

我的數組$ product_ingredient包含一些值。

foreach ($product_ingredient as $key) {   
       $ingredient_level1 = $this->ProductIngredientVersion->query('SELECT * FROM ingredients_ingredients 
       WHERE ingredients_ingredients.ingredient_id = :ingredient_id 
       AND ingredients_ingredients.product_id = :id 
       AND ingredients_ingredients.version_id = :version_id 
       AND ingredients_ingredients.level = 1', array('id' => $id, 'ingredient_id' => $key['products_ingredients']['ingredient_id'], 'version_id' => $key['products_ingredients']['version_id'])); 


       foreach($ingredient_level1 as $key2){ 
        $ingredient_level2 = array($this->ProductIngredientVersion->query('SELECT * FROM ingredients_ingredients 
        WHERE ingredients_ingredients.ingredient_id = :ingredient_id 
        AND ingredients_ingredients.product_id = :id 
        AND ingredients_ingredients.version_id = :version_id 
        AND ingredients_ingredients.level = 2', array('id' => $id, 'ingredient_id' => $key2['ingredients_ingredients']['ingredient2_id'], 'version_id' => $key2['ingredients_ingredients']['version_id']))); 
        array_push($ingredient_level1, $ingredient_level2); 
       } 
       array_push($ingredient_ingredient, $ingredient_level1); 
      } 

結果是:

array(
    (int) 0 => array(
     (int) 0 => array(
      'ingredients_ingredients' => array(
       'id' => '34', 
       'level' => '1' 
      ) 
     ), 
     (int) 1 => array(
      (int) 0 => array(
       (int) 0 => array(
        'ingredients_ingredients' => array(
         'id' => '35', 
         'level' => '2' 
        ) 
       ) 
      ) 
     ) 
    ) 

但我想這個結果

array(
    (int) 0 => array(
     (int) 0 => array(
      'ingredients_ingredients' => array(
       'id' => '34', 
       'level' => '1', 
       array(
        'ingredients_ingredients' => array(
         'id' => '35', 
         'level' => '2' 
        ) 
      ) 
     ) 
    ) 

我該如何解決?

+0

你在尋找'array_merge'(http://php.net/manual/en/function.array-merge.php)嗎?我不確定你要用樣本數組去做什麼,因爲你要創建的數組是無效的(多個鍵名相同,等等) – 2013-02-20 22:43:47

+0

array_merge只追加數組我想要數組在另一個數組內@Dave – 2013-02-20 22:46:17

+0

在你想要的結果代碼中,我相信你有一個額外的數組('修改後的'行',並且應該用一個逗號代替它)正確嗎? – DACrosby 2013-02-20 22:48:05

回答

2

通過

array_push(
    $ingredient_ingredient[0][0]['ingredients_ingredients'], 
    $ingredient_level1 
); 

這推動所述陣列到適當的級聯級替換

array_push($ingredient_ingredient, $ingredient_level1); 

。但是,如果您無法在其他地方修改SQL或數組結構,那麼很有可能這是最有效的方法。