簡體   English   中英

如何使用 array_push 向數組添加值和鍵

[英]How to use array_push to add value and key to array

一旦此代碼運行,我就會收到錯誤消息。 我已經查找了可能的解決方案,但一切似乎都正確格式化。

$searched = 'searched';    
$count    = '59';
$prop     = Array();

$i = 0;
while ($i++ <= 4) {
    array_push($prop[$i] = Array(
         'text' => $searched,
         'href' => 'http://mysite.com/?search=' . str_replace(' ', '+', $searched)
    ));
}

array_push($prop['Total Searches'] = $count);

我在 while 循環中收到此錯誤 5 次,而在 while 循環下的 array_push 收到 1 次。

Warning: Wrong parameter count for array_push()

代碼正常工作。 但它仍然會出現錯誤? 那么我應該壓制錯誤嗎?

改變:

array_push($prop['Total Searches'] = $count);

至:

$prop['Total Searches'] = $count;

等等

您僅使用 array_push 將值推送到列表樣式數組的末尾。 這在這里無關緊要,因為您只是在設置一個新的鍵/值對。

你正在混合方法。

閱讀有關array_push的信息,它不會像您認為的那樣做。

array_push($array, $val)就像$array[] = $val

只想

$prop[$i] = Array(
     'text' => $searched,
     'href' => 'http://mysite.com/?search=' . str_replace(' ', '+', $searched)
));

$prop['Total Searches'] = $count;

這會做你的工作,

$searched = 'searched';    
$count    = '59';
$prop     = Array();
$search_terms = Array();

$i = 0;
while ($i <= 4) 
{
   $search_terms['text'] = $searched;
   $searched = str_replace(' ', '+', $searched);
   $search_terms['href'] = 'http://mysite.com/?search='.$searched;
   array_push($prop, $search_terms);
   $i++;
}

$prop['Total Searches'] = $count;

並檢查http_build_query ,這就是我正在使用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM