PHP使用array_push向多维数组添加元素

PHP使用array_push向多维数组添加元素,php,multidimensional-array,array-push,Php,Multidimensional Array,Array Push,我有一个多维数组$md_array,我想在子数组recipe_类型中添加更多元素,这些元素来自一个从表中读取数据的循环 在循环中,我为每行创建一个新表$newdata: $newdata = array ( 'wpseo_title' => 'test', 'wpseo_desc' => 'test', 'wpseo_metakey' => 'test' ); 然后,使用array\u push()

我有一个多维数组$md_array,我想在子数组recipe_类型中添加更多元素,这些元素来自一个从表中读取数据的循环

在循环中,我为每行创建一个新表$newdata:

$newdata =  array (
          'wpseo_title' => 'test',
          'wpseo_desc' => 'test',
          'wpseo_metakey' => 'test'
        );
然后,使用
array\u 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\u push将新元素(数组)添加到recipe\u类型数组的语法是什么?我无法理解多维数组,我有点困惑。

在多维数组中,条目是另一个数组,请将该值的索引指定给array\u push:

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

如果要在关联数组中按增量顺序添加数据,可以执行以下操作:

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

我知道这个话题很古老,但我只是在谷歌搜索后发现了它,所以。。。下面是另一个解决方案:

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

这个看起来很干净,很好用

这里有一个问题:在array_push之前,我要向数据库添加一个新行,这一行需要通过id链接到数组元素。因此,如果
$id=mysql\u insert\u id()
,那么我会
$md\u数组[“配方类型”][$id]=$newdata
,对吗?如何为
$md\u数组[$number]
提供自定义索引?我得到了以下错误:
array\u push()期望参数1是array,如果给定为null
$number
变量来自
foreach($number为$number)
,其中
$numbers
是一个简单的数字数组。例如,
$numbers=[1,2,3,4,5]
。啊,我是从你那儿弄来的。