PHP array from jquery serialize, both work but which is correct?
I am using this to get a string from jquery to a php array via json.
$navMenuLay开发者_如何学运维out = array();
parse_str($layout['navMenu'], $navMenuLayout);
print_r($navMenuLayout);
But I noticed if I take out the first line then I still get the same output, does the first line matter?
parse_str($layout['navMenu'], $navMenuLayout);
print_r($navMenuLayout);
Of course, you don't have to predefine the variable for this function because PHP sets them automatically.
See the example from PHP.net for what happens when the second argument is defined/undefined:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
So, if you don't define the second argument, each key=>value pair in the string is made into an actual variable, whereas if you define a variable to be set, they are put into an array as that variable. PHP will automatically create everything for the function, you don't have to pre-define anything.
parse_str
is defined in the php manual as:
void parse_str ( string $str [, array &$arr ] )
The square brackets around the array argument mark it as optional. The &
marks it as a reference argument, implying that an array will be created if a variable is passed in from the calling code.
So either is correct, but the first tells any maintainer of the code more about what you are expecting to send/get back from the function call without having to look it up in the manual.
The $navMenuLayout = array();
declares the variable. You can get away without declaring it first but if you have notices enabled in your php.ini error configuration, you'll get a notice informing you that an undeclared variable is being used (see http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting for setting your error logging levels).
$navMenuLayout
is passed to the function with the intention replacing it's value with a result from the function.
If you look at http://www.php.net/parse_str , you'll see in the declaration that there is an & before the variable name: parse_str ( string $str [, array &$arr ] )
. This means that the variable being passed will be over-written.
精彩评论