php 5.4 var_export的改進
阿新 • • 發佈:2021-11-29
用 var_export 來將資料儲存到 php 配置檔案裡的時候,發現var_export轉出來的變數定義還是 array()這種形式,不能轉為[],所以自己寫個函式來轉換一下,程式碼如下:
<?php function format_var_export($data = []) { $string = "<?php\n\nreturn " . var_export($data, TRUE) . ";"; $string = str_replace("=> \n array (", "=> [", $string); $string = str_replace("),", "],", $string); $string = str_replace(");", "];", $string); $string = str_replace("array (", "[", $string); $string = str_replace(" ", " ", $string); return $string; }
實驗一下
config.php 程式碼如下:
<?php $data = [ 'user' => [ 'name' => 'hello', 'uid' => 1 ], 'tel' => [ 'type' => 'phone', 'number' => '123456', ] ]; $string = format_var_export($data); echo $string; function format_var_export($data = []) { $string = "<?php\n\nreturn " . var_export($data, TRUE) . ";"; $string = str_replace("=> \n array (", "=> [", $string); $string = str_replace("),", "],", $string); $string = str_replace(");", "];", $string); $string = str_replace("array (", "[", $string); $string = str_replace(" ", " ", $string); return $string; }
執行指令碼 php config.php
輸出
好了,這就是我們要的,將這個資料儲存到配置檔案就行了。