0

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.

4

2 回答 2

1

命令行参数是字符串并且只是字符串。

当您要传入分层元素时,唯一的选择是解析字符串。然而 JSON 编码很好,简单且紧凑。

在命令行上传递以下内容,然后使用json_decode解析将为您提供所需的结果;

{"Name":"Lion","Category":{"teeth":"long_teeth","height":"short"}}

简单证明:

$opt = '{"Name":"Lion","Category":{"teeth":"long_teeth","height":"short"}}';
print_r(json_decode($opt));
于 2012-07-03T07:01:21.693 回答
0

命令行参数只能是字符串,无法直接在命令行上传递任何复杂的数据结构,如数组。您可以将数组序列化为字符串,并在程序中取消序列化该参数。因此,您可以将数组作为字符串传递。最明显的候选是 JSON 格式,请参阅json_decode.

于 2012-07-03T06:19:17.117 回答