开发者

Query string processing

开发者 https://www.devze.com 2023-01-12 12:46 出处:网络
While doing some query string processing I stumbled upon this: <?php $in=\'a=6&b=7&8=c\'; parse_str($in,$qs);

While doing some query string processing I stumbled upon this:

<?php
$in='a=6&b=7&8=c';
parse_str($in,$qs);
$out=array_merge($qs,array('9'=>'d'));
print_r($out);
?>

We get:

Array
(
    [a] => 6
    [b] => 7
    [0] => c
    [1] => d
)

Instead of:

Array
(
    [a] => 6
    [b] => 7
    [8] => c
    [9] => d
)

I understand why this is happening ('8' and '9' are being treated as numeric keys) but I'm not happy that I ha开发者_运维技巧ve to do this the long way round.

There must be a way to keep it simple. How do you slice, dice and cook your query strings?


Consider using the UNION operator for arrays

$out=$qs+array('9'=>'d');
print_r($out);


Why dont you just do a simple loop over one array and checking of key exists or not?

If it exists then update the value otherwise add a new array element. Thats waht I do to avoid problems like these.


I am using http_build_query() function.
And NEVER use numeric keys for the query string/any request variables.


The issue is that array_merge renumbers numeric keys so that they start from zero (if you var_dump your $qs array before the merge, you will see that there is a key named 8). Either don't use numeric keys, or just push straight onto the array instead of using array_merge:

$in = 'a=6&b=7&8=c';
parse_str($in,$qs);
$out = $qs;
$out[9] = 'd';

Note that parse_str also has the side effect of setting variables in the local scope, so after you parse your query string, $a will be 6 and $b will be 7. This may or may not be desired.

0

精彩评论

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