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

新手上路,请多包涵

我有一个多维数组 $md_array,我想将更多元素添加到子数组 recipe_type 和来自从表中读取数据的循环中的美食。

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

原文由 bikey77 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 782
2 个回答

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

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

原文由 Dinesh 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 dtech 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题