使用新语法转换PHP数组

5
我正在寻找一种方法(正则表达式、代码片段、插件等)来使用SublimeText将旧的数组转换为新的PHP语法。
// Old synthax
$var = array(
   'foo' => 'bar' 
);

// New synthax
$var = [
   'foo' => 'bar'
];

有人有想法吗?

@Kafin 你应该将你的编辑改成一个答案并接受它。 - Chnossos
我认为新用户还不能接受自己的答案,对吧? - dcclassics
可以的,但需要两天时间 :) - Kafin
3个回答

6

5

我发现使用php codesniffer也可以实现这一点:https://github.com/squizlabs/PHP_CodeSniffer

phpcbf src/ --standard=Generic --sniffs=Generic.Arrays.DisallowLongArraySyntax

在这个例子中,你需要将src/替换为包含脚本的文件夹。或者你可以提供一个文件名。

如果您使用PhpStorm,它将自动根据配置文件中的规则将其转换为新格式。 - Vishnu R

0
也许有点晚了,但我创建了自己的代码。可能不是很漂亮,但它确实完成了我的工作。如果你不喜欢制表符,请将缩进函数中的 \t 更改为2或4个空格。
    function loopArray(array $array, $loopcount = 0) {

        $returnString = ($loopcount == 0) ? "[\n" : "";

        $tabKey = indent($loopcount + 2);
        $tabValue = indent($loopcount + 3);

        $lastKey = array_key_last($array);

        foreach ($array as $key => $value) {

            $totalChildren = count($array[$key]);

            $returnString .= $tabKey . '"' . $key . '" => ';

            if ($totalChildren == 0) $returnString .= '[]';
            if ($totalChildren > 0 && is_array($array[$key])) $returnString .= '[' . "\n";

            if (is_array($value)) {

                $returnString .= loopArray($value, $loopcount + 1);
            } else {

                if ($totalChildren == 1) $returnString .=  '"' . $value . '"';
                if ($totalChildren > 1)  $returnString .=  $tabValue . '"' . $value . '"'  . ",\n";
            }

            $returnString .= ($lastKey == $key) ? "\n" . indent($loopcount+1) . "]" : ",\n";
        }

        return $returnString;
    }

    function indent($amount) {

        return str_repeat("\t", $amount);
    }

/** use function below only prior to php 7.3 */

    function array_key_last(array $array) {

        $key = NULL;

        if ( is_array( $array ) ) {

            end( $array );
            $key = key( $array );
        }

        return $key;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接