Skip to content

Commit 40e481c

Browse files
committed
Initial commit.
0 parents  commit 40e481c

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/input.json
2+
.idea

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Json to PHP Array
2+
3+
__将Json转为等价的PHP array表示__
4+
5+
## Usage
6+
7+
1. 安装Python3,此项目仅使用了Python标准库,所以无需安装依赖
8+
2. 在当前目录新建文件`input.json`,向其中写入要转换json
9+
3. 执行`python3 main.py`,即可打印出输入json对应的PHP array表示

main.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import json
2+
3+
4+
def format_php_array(data, indent=0):
5+
php_array = '['
6+
if isinstance(data, dict):
7+
for i, (key, value) in enumerate(data.items()):
8+
php_array += '\n' + ' ' * (indent + 1)
9+
php_value = format_php_value(value, indent + 1)
10+
php_array += f"'{key}' => {php_value}"
11+
if i < len(data) - 1:
12+
php_array += ','
13+
elif isinstance(data, list):
14+
for i, item in enumerate(data):
15+
php_array += '\n' + ' ' * (indent + 1)
16+
php_value = format_php_value(item, indent + 1)
17+
php_array += php_value
18+
if i < len(data) - 1:
19+
php_array += ','
20+
else:
21+
return format_php_value(data, indent)
22+
php_array += '\n' + ' ' * indent + ']'
23+
return php_array
24+
25+
26+
def format_php_value(value, indent):
27+
if isinstance(value, bool):
28+
return "true" if value else "false"
29+
elif value is None:
30+
return "null"
31+
elif isinstance(value, (int, float)):
32+
return str(value)
33+
elif isinstance(value, (dict, list)):
34+
return format_php_array(value, indent)
35+
elif isinstance(value, str):
36+
return f"'{value}'"
37+
else:
38+
return str(value)
39+
40+
41+
if __name__ == "__main__":
42+
json_data = json.load(open("./input.json", "r"))
43+
44+
# 格式化PHP数组
45+
formatted_php_array = format_php_array(json_data)
46+
print("<?php\n$myArray = " + formatted_php_array + ";\n?>")

0 commit comments

Comments
 (0)