我需要将$ _SERVER ['argv']数组解析为单个数组。
我可以决定如何获取参数。
例如,脚本的调用方式如下:php script.php name:jack operation:full
我在$ _SERVER ['argv']中获取参数如下:
Array
(
[0] => script.php
[1] => name:jack
[2] => operation:full_res
)
如何轻松地将这些参数移动到一个如下所示的数组中:
$ param:
Array(['name'] => jack ['operation'] => full_res)
答案 0 :(得分:2)
您可能正在寻找getopt
,尽管它会稍微改变您的参数格式。
<?php
var_dump(getopt('',array('name::','operation::')));
?>
从命令行:
$ php opt.php --name=foo --operation=bar
array(2) {
["name"]=>
string(3) "foo"
["operation"]=>
string(3) "bar"
}
答案 1 :(得分:2)
很多人喜欢PHP CLI参数的实用程序功能:
<?php
/**
* parseArgs Command Line Interface (CLI) utility function.
* @usage $args = parseArgs($_SERVER['argv']);
* @author Patrick Fisher <patrick@pwfisher.com>
* @source https://github.com/pwfisher/CommandLine.php
*/
function parseArgs($argv = null) {
$argv = $argv ? $argv : $_SERVER['argv']; array_shift($argv); $o = array();
foreach ($argv as $a) {
if (substr($a, 0, 2) == '--') { $eq = strpos($a, '=');
if ($eq !== false) { $o[substr($a, 2, $eq - 2)] = substr($a, $eq + 1); }
else { $k = substr($a, 2); if (!isset($o[$k])) { $o[$k] = true; } } }
else if (substr($a, 0, 1) == '-') {
if (substr($a, 2, 1) == '=') { $o[substr($a, 1, 1)] = substr($a, 3); }
else { foreach (str_split(substr($a, 1)) as $k) { if (!isset($o[$k])) { $o[$k] = true; } } } }
else { $o[] = $a; } }
return $o;
}
这将满足您的要求和更多。请参阅示例用法和https://github.com/pwfisher/CommandLine.php处的帮助程序类。
答案 2 :(得分:1)
$param = array();
foreach($_SERVER['argv'] as $value) {
if(substr_count($value, ':') !== 1)
continue;
$vals = explode(':', $value);
$param[$vals[0]] = $vals[1];
}
答案 3 :(得分:1)
$args = array();
$_args = array_slice($_SERVER['argv'], 1);
foreach ($_args as $_arg) {
$arg = explode(':', $_arg);
if (count($arg) > 1)
$args[ $arg[0] ] = $arg[1];
else
$args[] = $arg[0];
}