I want to pass an array from command line to php as:
c:\<path>\php.exe somefile.php --filter array{['name']=>"lion",['category']=>array{['teeth']=>'long_teeth',['height']=>'short'}}
and now in code I want variable filter as an array as I passed through command line like:
$opt['filter'] = array {
['name']=>"lion",
['category']=>
array{
['teeth']=>'long_teeth',
['height']=>'short'
}
}
But the problem is passed argument becomes string and I am not able to parse it to array. I am using getopt() function to get filter as an attribute to array variable $opt like:
$shortopts = "abc"; // These options do not accept values
$longopts = array(
"filter:", // Required value
);<br>
$opt = getopt($shortopts, $longopts);
actually whole scenario is to take a variable as an array or string or a boolean value and pass it to another php script as it is and that script I am calling through exec function like: exec(c:\\<path>\\php.exe myphpscript.php --filter $array_variable );
and then in myphpscript.php, I want to use $array_variable
as it was in earlier script so that I can use it as it was.
Command line arguments are strings and only strings.
As you want to pass in a hierarchical element the only option is to parse the string. However JSON encoding is nice, easy and compact.
Passing the following on the command line and then parsing with json_decode will give you the required results;
{"Name":"Lion","Category":{"teeth":"long_teeth","height":"short"}}
simple proof:
$opt = '{"Name":"Lion","Category":{"teeth":"long_teeth","height":"short"}}';
print_r(json_decode($opt));
Command line arguments can only be strings, there's no way to pass any complex data structures like arrays directly on the command line. You can serialize an array into a string though and unserialize that argument in your program. So you can pass an array around as a string. The most obvious candidate is the JSON format, see json_decode
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.