标签:
背景:通过接口获取到的二维数组处理后并以json格式返给浏览器,其中有些数据需删除。为了方便首先想到的是unset,那么问题就来了
//数组 $arr = array( "0" => array("b" => "b", "c" => "c", "d" => "d"), "1" => array("e" => "e", "f" => "f", "g" => "g"), "2" => array("h" => "h", "i" => "i", "j" => "j") ); //打印如下 array(3) { [0]=> array(3) { ["b"]=> string(1) "b" ["c"]=> string(1) "c" ["d"]=> string(1) "d" } [1]=> array(3) { ["e"]=> string(1) "e" ["f"]=> string(1) "f" ["g"]=> string(1) "g" } [2]=> array(3) { ["h"]=> string(1) "h" ["i"]=> string(1) "i" ["j"]=> string(1) "j" } } //json_encode()后 [ {"b":"b", "c":"c", "d":"d"}, {"e":"e", "f":"f", "g":"g"}, {"h":"h", "i":"i", "j":"j"} ]
使用了unset($arr[1])后
1 //删除后打印如下 2 array(2) { 3 [0]=> array(3) { ["b"]=> string(1) "b" ["c"]=> string(1) "c" ["d"]=> string(1) "d" } 4 [2]=> array(3) { ["h"]=> string(1) "h" ["i"]=> string(1) "i" ["j"]=> string(1) "j" } 5 } 6 //json_encode()后 7 { 8 "0":{"b":"b","c":"c","d":"d"}, 9 "2":{"h":"h","i":"i","j":"j"} 10 }
可以看到 unset后 在json_encode数据格式变了,研究了下, 大概是因为数组unset后,为了保证数组的元素顺序所以加上了原数字key,以确认去掉的是哪一个元素
为了不出现这样的情况我们就得将数组重新索引了
$arr = array_values($arr); //这样重新索引以后json_encode() [ {"b":"b","c":"c","d":"d"}, {"h":"h","i":"i","j":"j"} ]
特殊情况,特殊处理,虽然在我这个问题上unset后强制保留了key是多余的,但是很佩服php的高瞻远瞩
标签:
原文地址:http://www.cnblogs.com/ID890/p/unset.html