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

问题描述 投票:48回答:3

我有一个多维数组$ md_array,我想向来自读取表数据的循环的子数组配方_类型和美食添加更多元素。

在循环中,我为每行创建一个新表$ 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向食谱类型数组添加新元素(数组)的语法是什么?我永远无法绕过多维数组,我有点困惑。

php multidimensional-array array-push
3个回答
76
投票

如果要在关联数组中以递增顺序添加数据,则可以执行此操作:

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

16
投票

在多维数组中,条目是另一个数组,请将该值的索引指定为array_push:

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

0
投票

我知道这个主题很旧,但是在Google搜索之后我就发现了这个主题,所以...这是另一种解决方案:

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

这个对我来说似乎很干净,它很好用!

© www.soinside.com 2019 - 2024. All rights reserved.