|
| 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