Is it possible to pass an array as a command line argument to a PHP script?

前端 未结 9 864
忘掉有多难
忘掉有多难 2020-12-09 16:37

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 all

相关标签:
9条回答
  • 2020-12-09 17:02

    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'
    )
    
    0 讨论(0)
  • 2020-12-09 17:05

    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"
    }
    */
    
    0 讨论(0)
  • 2020-12-09 17:06

    The following code block will do it passing the array as a set of comma separated values:

    <?php
      $i_array = explode(',',$argv[1]);
      var_dump($i_array);
    ?>
    

    OUTPUT:

    php ./array_play.php 1,2,3
    
    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
      [2]=>
      string(1) "3"
    }
    
    0 讨论(0)
提交回复
热议问题