[英]How do I insert a multidimensional array into another array in a loop?
我有以下代碼:
$postList = array();
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$newPost = array( "ID" => $counter,
"Text" => $text,
"url" => $url );
$postList = array_merge($postList, $newPost);
$counter += 1;
}
這段代碼不起作用,我在postList數組中找到的是最后一個發布項目,而不是列表。 如何將所有項目插入數組?
提前致謝
嘗試這個
$postList = array();
$counter = 0;
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$newPost = array( "ID" => $counter,
"Text" => $text,
"url" => $url);
$postList[] = $newPost;
$counter += 1;
}
保存創建額外的變量,請嘗試:
$postList = array();
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$postList[] = array( "ID" => $counter,
"Text" => $text,
"url" => $url );
$counter += 1;
}
在面向對象的編程語言中,Array對象中存在push方法。 所以就是這樣。
array.push(element);
這意味着在數組末尾推送元素。 在PHP中也有push方法,但是它是靜態函數,PHP庫就是這樣。 因此,您可以執行以下操作:
$persons = Array();
$person = Array('id' => 1, 'name' => 'my name');
array_push($persons, $person);
要么
$array[] = $element;
第一個是更明確的,您將更好地了解它的作用。 您應該閱讀有關PHP中數據結構的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.