Php-将变量输出成array结构

前言

今天写需求的时候遇到个问题,前端给了我一段json,需要我配置到php项目里面,而我则需要去把它变成array。虽然用的时候可以直接json_decode但是感觉还是会损失一定的性能,而一个个去改的话又觉得很麻烦,所以写了一段下面的代码,可以让json自动转换成array,这样配置的时候可以直接cp输出内容去配置,用起来也比较方便

outPutArray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

<?php
/**
* Created by PhpStorm.
* User: shiwenyuan
* Date: 2019/9/11 13341007105@163.com
* Time: 17:33
*/

class Utils
{
/**
* 把array或json以array字符串的形式输出 等同于var_export
* @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');
/*
* [
* '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,
* ],
* ],
* ]
*/