Is it possible to pass an array as a command line

2019-02-08 04:39发布

I'm maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I've just fixed a bug that would not allow it to fetch array variables from POST and GET and I'm wondering whether this is also applicable to the part that deals with the command line.

Can you pass an array as a command line argument to PHP?

9条回答
来,给爷笑一个
2楼-- · 2019-02-08 05:13

You need to figure out some way of encoding your array as a string. Then you can pass this string to PHP CLI as a command line argument and later decode that string.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-08 05:15

Strictly speaking, no. However you could pass a serialized (either using PHP's serialize() and unserialize() or using json) array as an argument, so long as the script deserializes it.

something like

php MyScript.php "{'colors':{'red','blue','yellow'},'fruits':{'apple','pear','banana'}}"

I dont think this is ideal however, I'd suggest you think of a different way of tackling whatever problem you're trying to address.

查看更多
欢心
4楼-- · 2019-02-08 05:15

So if a CLI is as such

php path\to\script.php param1=no+array param2[]=is+array param2[]=of+two

Then the function thats reads this can be

function getArguments($args){
    unset($args[0]); //remove the path to script variable
    $string = implode('&',$args);
    parse_str($string, $params);
    return $params;
}

This would give you

Array
(
    [param1] => no array
    [param2] => Array
             (
                 [0] => is array
                 [1] => of two
             )
)
查看更多
We Are One
5楼-- · 2019-02-08 05:15

Sort of.

If you pass something like this:

$php script.php --opt1={'element1':'value1','element2':'value2'}

You get this in the opt1 argument:

Array(
 [0] => 'element1:value1'
 [1] => 'element2:value2'
)

so you can convert that using this snippet:

foreach($opt1 as $element){
    $element = explode(':', $element);
    $real_opt1[$element[0]] = $element[1];
}

which turns it into this:

Array(
 [element1] => 'value1'
 [element2] => 'value2'
)
查看更多
霸刀☆藐视天下
6楼-- · 2019-02-08 05:16

As it was said you can use serialize to pass arrays and other data to command line.

shell_exec('php myScript.php '.escapeshellarg(serialize($myArray)));

And in myScript.php:

$myArray = unserialize($argv[1]);
查看更多
smile是对你的礼貌
7楼-- · 2019-02-08 05:27

Directly not, all arguments passed in command line are strings, but you can use query string as one argument to pass all variables with their names:

php myscript.php a[]=1&a[]=2.2&a[b]=c

<?php
parse_str($argv[1]);
var_dump($a);
?>

/*
array(3) {
  [0]=> string(1) "1"
  [1]=> string(3) "2.2"
  ["b"]=>string(1) "c"
}
*/
查看更多
登录 后发表回答