使用array_push将元素添加到多维数组中的PHP

73

我有一个多维数组$md_array,我想从一个循环中读取数据并向子数组recipe_type和cuisine添加更多元素。

在循环中,我为每一行创建一个新的表$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数组的语法是什么?我从来没有理解过多维数组,有点困惑。

4个回答

115

如果你想要在关联数组中按增量顺序添加数据,可以这样做:

$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],$arr [1]..您不能直接在关联数组中使用它。但是,由于您的子数组具有此类索引,因此仍然可以像这样使用

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

1
这里有一个问题:在使用array_push之前,我向数据库添加了一个新行,而此行需要通过id与数组元素进行关联。所以,如果 $id = mysql_insert_id(),那么我就可以执行 $md_array["recipe_type"][$id] = $newdata,是吗? - bikey77

20

在多维数组中,一个条目是另一个数组。要将值添加到该数组,请指定该值的索引并使用array_push函数:

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

2
你如何给$md_array[$number]一个自定义索引?我得到了以下错误:array_push() expects parameter 1 to be array, null given$number变量来自于foreach($numbers as $number),其中$numbers是一个简单的数字数组。例如,$numbers = [1,2,3,4,5]。啊哈,我从这个答案中明白了。 - Pathros

5

我知道这个话题很老了,但是我在谷歌搜索后刚刚发现它,所以......这里是另一个解决方案:

$array_merged = array_merge($array_going_first, $array_going_second);

这个看起来相当干净,我认为它运行得非常好!

-1

我用这个方法搞定了,代码也很简洁 $array_merged = array_merge($array_going_first, $array_going_second);


1
这不是与上面的答案相同吗? - Melaku Minas Kasaye
1
这不是与上面的答案相同吗? - Melaku Minas Kasaye
是的,只是确认一下最简单的方法来回答问题,我没有足够的声望将答案设为最有用的。 - outzo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接