原文出處 https://shiwenyuan.github.io/post/ck0f6wrb...
今天寫需求的時候遇到個問題,前端給了我一段json,需要我配置到php專案裡面,而我則需要去把它變成array。雖然用的時候可以直接json_decode但是感覺還是會損失一定的效能,而一個個去改的話又覺得很麻煩,所以寫了一段下面的程式碼,可以讓json自動轉換成array,這樣配置的時候可以直接cp輸出內容去配置,用起來也比較方便
<?php
/**
* Created by PhpStorm.
* User: shiwenyuan
* Date: 2019/9/11 13341007105@163.com
* Time: 17:33
*/
class Utils
{
/**
* 把array或json以array字串的形式輸出
* @param $str
* @return string
*/
public static function outPutArray($str): string
{
if (is_string($str)) {
$arr = json_decode($str, true);
if (is_null($arr)) {
$ret_str = '';
if (is_numeric($str)) {
$ret_str .= '[' .PHP_EOL. $str .PHP_EOL. ']';
} else {
$ret_str .= '[' .PHP_EOL. '\''.$str .'\''.PHP_EOL. ']';
}
return $ret_str;
}
} else {
$arr = $str;
}
$str = '[' . PHP_EOL;
foreach ($arr as $key => $value) {
if (!is_numeric($key)) {
$str .= "'{$key}' => ";
}
if (is_array($value)) {
$str .= self::outPutArray($value);
} else {
if (is_string($value)) {
$str .= "'{$value}'," . PHP_EOL;
} else {
$str .= "{$value}," . PHP_EOL;
}
}
}
$str .= '],' . PHP_EOL;
return $str;
}
}
echo Utils::outPutArray('shiwenyuan');
/*
* output: [
* 'shiwenyuan'
* ]
* */
echo Utils::outPutArray(['name'=>'zhangsan', 'age'=>18, 'friend'=>[['name'=>'lisi', 'age'=>19], ['name'=>'wangwu', 'age'=>20]]]);
/**
* [
*'name' => 'zhangsan',
* 'age' => 18,
* 'friend' => [
* [
* 'name' => 'lisi',
* 'age' => 19,
* ],
* [
* 'name' => 'wangwu',
* 'age' => 20,
* ],
* ],
* ]
*/
echo Utils::outPutArray('{"name":"zhangsan","age":18,"friend":[{"name":"lisi","age":19},{"name":"wangwu","age":21}]}');
/**
* [
*'name' => 'zhangsan',
* 'age' => 18,
* 'friend' => [
* [
* 'name' => 'lisi',
* 'age' => 19,
* ],
* [
* 'name' => 'wangwu',
* 'age' => 20,
* ],
* ],
* ]
*/