問題描述
我有一個多維數組 $md_array,我想向來自從表中讀取數據的循環的子數組 recipe_type 和美食添加更多元素.
I have a multidimensional array $md_array and I want to add more elements to the sub-arrays recipe_type and cuisine coming from a loop that reads data from a table.
在循環中,我為每一行創建一個新表 $newdata:
In the loop, I create a new table $newdata for each row:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
然后,使用 array_push()
我需要將 $newdata 數組附加到以下多維數組:
and then, using array_push()
I need to append the $newdata arrays to the following multidimensional array:
$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 數組添加新元素(數組)的語法是什么?我永遠無法理解多維數組,我有點困惑.
Whats the syntax for adding a new element (array) to the recipe_type array with array_push? I could never get my head around multidimensional arrays and I'm a bit confused.
推薦答案
如果你想在關聯數組中以遞增順序添加數據,你可以這樣做:
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
這將被添加到食譜或菜肴中,具體取決于最后一個索引是什么.
this will get added to the recipe or cuisine depending on what was the last index.
Array push 通常用在有順序索引的數組中: $arr[0] , $ar[1] .. 不能直接在關聯數組中使用.但是由于您的子數組具有這種索引,您仍然可以像這樣使用它
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
這篇關于PHP 使用 array_push 向多維數組添加元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!