2013-04-30 216 views
36

我有一個多維數組$ md_array,我想向從子表中讀取數據的循環中的子數組recipe_type和cuisine添加更多元素。PHP將元素添加到具有array_push的多維數組

在循環中,我創建於各行的新表$ newdata:

$newdata = array (
      'wpseo_title' => 'test', 
      'wpseo_desc' => 'test', 
      'wpseo_metakey' => 'test' 
     ); 

,然後使用array_push()我需要將$ newdata數組追加到以下多維數組:

$md_array= array (
    'recipe_type' => 
     array (
     18 => 
     array (
      'wpseo_title' => 'Salads', 
      'wpseo_desc' => 'Hundreads of recipes for Salads', 
      'wpseo_metakey' => '' 
     ), 
     19 => 
     array (
      'wpseo_title' => 'Main dishes', 
      'wpseo_desc' => 'Hundreads of recipes for Main dishes', 
      'wpseo_metakey' => '' 
     ) 
    ), 
    'cuisine' => 
     array (
     22 => 
     array (
      'wpseo_title' => 'Italian', 
      'wpseo_desc' => 'Secrets from Sicily in a click', 
      'wpseo_metakey' => '' 
     ), 
     23 => 
     array (
      'wpseo_title' => 'Chinese', 
      'wpseo_desc' => 'Oriental dishes were never this easy to make', 
      'wpseo_metakey' => '' 
     ), 
     24 => 
     array (
      'wpseo_title' => 'Greek', 
      'wpseo_desc' => 'Traditional Greek flavors in easy to make recipies', 
      'wpseo_metakey' => '' 
     ) 
    ) 
    ); 

用array_push將新元素(數組)添加到recipe_type數組的語法是什麼?我永遠無法理解多維數組,並且我有點困惑。

回答

54

,如果你想在增量順序添加您的關聯數組,你可以在裏面的數據做到這一點:

$newdata = array (
     'wpseo_title' => 'test', 
     'wpseo_desc' => 'test', 
     'wpseo_metakey' => 'test' 
    ); 

// for recipe 

$md_array["recipe_type"][] = $newdata; 

//for cuisine 

$md_array["cuisine"][] = $newdata; 

這將添加到根據什麼是最後一個索引的配方或美食。

當你有序列索引時,數組通常用在數組中:$ arr [0],$ ar [1] ..你不能直接在關聯數組中使用它。但由於你的子陣列有這種指標,你仍然可以使用它像這樣

array_push($md_array["cuisine"],$newdata); 
+0

這裏有一個問題:到array_push之前,我加入一個新行到數據庫,該行需要通過鏈接id到數組元素。所以,如果'$ id = mysql_insert_id()',那麼我做'$ md_array [「recipe_type」] [$ id] = $ newdata',對嗎? – bikey77 2013-04-30 20:54:06

11

由於多維數組中的一個條目是另一個數組,指定值的指數array_push:

array_push($md_array['recipe_type'], $newdata);