php常用函数之一json_encode将数组转换json格式,本篇主要讲解一下在空数组,关联数组和索引数组的区别:
$arr = ['a','b','c','d']; $tarr = ['a' => 'a', 'b' => 'b']; var_dump(json_encode($tarr)); echo '<br/>'; var_dump(json_encode([])); echo '<br/>'; var_dump(json_encode($arr));var_dump(json_encode((object) $arr)); OR var_dump(json_encode($arr, JSON_FORCE_OBJECT));
exit;返回值如下:
string(17) "{"a":"a","b":"b"}"
string(2) "[]" string(17) "["a","b","c","d"]"string(33) "{"0":"a","1":"b","2":"c","3":"d"}" 强制转换
主要在于索引数组返回的值还是数组,空数组返回[].....以后使用中一定要注意哈,还有json_encode在格式化中文的时候仅支持utf-8,要记得转义一下....否则非utf-8的中文会丢失