PHPアレイを新しい構文で変換します
-
21-12-2019 - |
質問
私は、旧PHP構文で古い配列をSublimeTextで変換する方法(正規表現、スニペット、プラグインなど)を探しています。
// Old synthax
$var = array(
'foo' => 'bar'
);
// New synthax
$var = [
'foo' => 'bar'
];
.
誰かがアイデアを持っていますか?
解決
私は仕事を完全に行うスクリプトを見つけました!
https://github.com/thomasbachem/php-short-Array-構文-converter
他のヒント
PHPコードニフファーでこれを行うことも可能であることを発見しました: https://github.com/ SquizLabs / PHP_CODESNiffer
phpcbf src/ --standard=Generic --sniffs=Generic.Arrays.DisallowLongArraySyntax
.
この例では、SRC /スクリプトを含むフォルダに置き換える必要があります。あるいは、ファイル名を指定することもできます。
多分遅れたが、私は自分のものを作りました。たぶんきれてはいけませんが、それは私が欲しい仕事をします。タブが好きでない場合は、Indent関数で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($ammount) {
return str_repeat("\t", $ammount);
}
/** 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;
}
. 所属していません StackOverflow