/** * 将数组转换成json字符串 * @param array $data 待转换的数组 * @param int $indent 缩进量 * @param int $level 当前层级 * @return string 转换后的json字符串 */function arraytojson($data, $indent = 0, $level = 0){ $result = ; $space = str_repeat( , $indent); $isassoc = is_assoc($data); if ($isassoc) { $result .= {\n; } else { $result .= [\n; } foreach ($data as $key => $value) { if ($isassoc) { $result .= $space . json_encode($key) . : ; } if (is_array($value)) { $result .= arraytojson($value, $indent + 4, $level + 1); } else if (is_bool($value)) { $result .= json_encode($value ? true : false); } else if (is_null($value)) { $result .= null; } else if (is_numeric($value)) { $result .= json_encode($value); } else { $result .= json_encode($value, json_unescaped_unicode); } if (next($data)) { $result .= ,; } $result .= \n; } $result .= str_repeat( , $level * 4); if ($isassoc) { $result .= }; } else { $result .= ]; } return $result;}/** * 判断一个数组是否是关联数组 * @param array $data 待判断的数组 * @return bool */function is_assoc($data){ if (!is_array($data)) { return false; } $keys = array_keys($data); $len = count($keys); for ($i = 0; $i < $len; $i++) { if ($keys[$i] !== $i) { return true; } } return false;}
这个方法接受一个数组作为参数,以及一个“缩进量”参数和一个“当前层级”参数,这两个参数用于格式化输出。其中,is_assoc()方法用于判断一个数组是否是关联数组。如果是,我们在输出时需要同时输出数组元素的键和值。而对于值的类型,我们采取不同的编码方法:
如果是子数组,递归调用arraytojson()方法进行进一步处理。如果是布尔类型,将其转换为字符串“true”或“false”进行输出。如果是null,直接输出“null”。如果是数字,用json_encode()函数进行编码输出。如果是其他类型,同样使用json_encode()函数,但传递一个json_unescaped_unicode选项参数,保留非ascii字符的原始unicode代码。此外,我们需要在每个子项的末尾输出一个逗号,以便支持多个牵连元素的序列化。最后,我们根据数组的类型输出相应的“结束符号”,并返回格式化后的json字符串。
使用上述代码,我们可以将一个php数组转换为json字符串,如下所示:
$data = array( 'name' => 'john', 'age' => 28, 'married' => true, 'hobbies' => array('basketball', 'music', 'reading'), 'address' => array( 'city' => 'beijing', 'country' => 'china' ), 'friends' => array( array('name' => 'tom', 'age' => 27), array('name' => 'jane', 'age' => 26) ));echo arraytojson($data);
结果输出如下:
{ name: john, age: 28, married: true, hobbies: [ basketball, music, reading ], address: { city: beijing, country: china }, friends: [ { name: tom, age: 27 }, { name: jane, age: 26 } ]}
在实际开发中,我们可能需要按照特定的格式要求输出json字符串。此时,自定义数组转json方法就变得非常有价值。
以上就是php怎么编写一个数组转json的方法的详细内容。
