PHP的命令行选项解析,howto [英] php's command line option parsing, howto

查看:74
本文介绍了PHP的命令行选项解析,howto的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PHP 5.2中使用Console_Getopt,对于它与其他语言(perl,bash,java)中的getopt有何不同感到惊讶。谁能推荐如何从返回的数组 $ opts中解析参数?

I'm using Console_Getopt in PHP 5.2, and finding it surprising about how different it is from getopt in other languages (perl, bash, java). Can anyone recommend how to parse the args from the array "$opts" returned?

php myprog.php -a varA -c -b varB

php myprog.php -a varA -c -b varB

$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r($opts);

// print_r返回以下值

// the print_r returns below

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => a
                    [1] => varA
                )

            [1] => Array
                (
                    [0] => c
                    [1] =>
                )

            [2] => Array
                (
                    [0] => b
                    [1] => varB
                )

        )

    [1] => Array
        (
        )

)

我开始做以下类似的事情,缠绕,所以我正在寻找有关在php中处理命令行标志的建议。

I started doing something like below, which is long-winded, so I'm looking for suggestions on dealing with command-line flags in php.

foreach($opts[0] as $i -> $keyval) {
    list($key, $val) = $keyval;
    if($key == 'a') {
        print "valueForA: $val\n";
    } else if($key == 'b') {
        print "valueForB: $val\n";         
    } else if($key == 'c') {
        print "c is set\n";
    }
}

我想知道为什么PHP的getopt不像perl那样,

I wonder why PHP's getopt isn't like perl's, where the array's key is the flag eg $opts{'a'} .. that would be convenient.

推荐答案

每行内联,其中数组的键是标志,例如$ opts {'a'} ..文档

Per the inline documentation


返回值是两个元素组成的数组:已解析的
选项列表和非选项命令列表行参数。解析的选项列表中
中的每个条目都是一对元素-第一个
指定选项,第二个指定选项参数,
(如果有)。

The return value is an array of two elements: the list of parsed options and the list of non-option command-line arguments. Each entry in the list of parsed options is a pair of elements - the first one specifies the option, and the second one specifies the option argument, if there was one.

这意味着您可以轻松地丢弃第二个数组,并承担保持数组数组,第一个元素选项,第二个元素值,格式的承诺。

Which means you easily discard the second array, and assume a commitment to the keeping the array of arrays, first element option, second element value, format.

有了这个假设,尝试

$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r(getHashOfOpts($opts));

function getHashOfOpts($opts) {
    $opts = $opts[0];
    $return_opts = $opts;
    $return_opts = Array();
    foreach($opts as $pair){
        $return_opts[$pair[0]] = $pair[1];
    }
    return $return_opts;
}

可以让您更喜欢数据结构。

to get an data structure more of your liking.

至于为什么这与getopt的其他实现不同,请问维护者

As for why this is different than other implementation of getopt, ask the maintainers.

这篇关于PHP的命令行选项解析,howto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆