2013-04-30 6 views
36

多次元配列$ md_arrayを持っていて、テーブルからデータを読み込むループから来るrecipe_typeと料理をサブアレイに追加したいと思います。ループにおいてPHPはarray_pushを使って多次元配列に要素を追加します

、Iは、行ごとに新しいテーブルの$ NEWDATA作成:私は次の多次元配列に$のNEWDATAアレイを追加する必要array_push()を使用して、その後

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

および:

$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配列に新しい要素(配列)を追加する構文は何ですか?私は多次元配列の周りに頭を浮かべることはできませんでした。私はちょっと混乱しています。あなたができるあなたの連想配列内のインクリメント順にデータを追加したい場合は

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

答えて

54

:エントリは別の配列は、多次元配列のように

+0

のようにそれを使用することができます質問です:以前は、私はデータベースに新しい行を追加しているarray_pushするには、この行はでリンクする必要がありますidを配列要素に追加します。ですから '$ id = mysql_insert_id()'なら '$ md_array [" recipe_type "] [$ id] = $ newdata'、正しいのですか? – bikey77

11

は、array_pushためにその値のインデックスを指定しますこれを行う:

$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);