开发者

How to use array_push to add value and key to array

I am receiving an error once this code runs. I have looked up possible solutions but everything seems to be formatted correctly.

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

I receive 开发者_开发知识库this error 5 times for the while loop, and 1 time for the array_push under the while loop.

Warning: Wrong parameter count for array_push()

The code works correctly! but it still calls out the error. So should I just suppress the error?


Change:

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

to:

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

etc.

You only use array_push to push a value on to the end of a list-style array. This is not relevant here, as you're just setting a new key/value pair.


You're mixing approaches.

Read about array_push, which doesn't do what you think it does.

array_push($array, $val) is like $array[] = $val.

You want just:

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

and

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


this will do your job,

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

and check http_build_query, thats what i am using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜