2014-09-13 86 views
2

我試圖刪除在我的json 2d數組中顯示的數字。我首先有一個動態的2d數組,並從該數組中刪除元素。然後它將數組轉換成json 2d數組。問題是我不想在開始時輸入數字。如何從json_encode中刪除數組索引php

像下面

[ 

"1": {"StateName":"Alaska","StateAbbr":"AK"}, 
"2": {"StateName":"Alabama","StateAbbr":"AL"}, 
"3": {"StateName":"Arkansas","StateAbbr":"AR"}, 
"4": {"StateName":"Arizona","StateAbbr":"AZ"}, 
"5": {"StateName":"California","StateAbbr":"CA"}, 
"6": {"StateName":"Colorado","StateAbbr":"CO"}, 
"7": {"StateName":"Connecticut","StateAbbr":"CT"} 

] 

我想它是這樣

[ 

{"StateName":"Alaska","StateAbbr":"AK"}, 
{"StateName":"Alabama","StateAbbr":"AL"}, 
{"StateName":"Arkansas","StateAbbr":"AR"}, 
{"StateName":"Arizona","StateAbbr":"AZ"}, 
{"StateName":"California","StateAbbr":"CA"}, 
{"StateName":"Colorado","StateAbbr":"CO"}, 
{"StateName":"Connecticut","StateAbbr":"CT"} 

] 

隨着出號。我怎樣才能做到這一點?

我試過mysql_fetch_assoc,但它不起作用。

$arr = array(); 
while($row = mysql_fetch_assoc($result)) { 
    $arr[] = $row; 
} 
echo json_encode($arr); 
+0

沒有,這不會工作動態密鑰在二維數組中。感謝回覆。 – user3210416 2014-09-13 13:57:10

回答

1

我發現如何從2d數組中刪除密鑰,一旦轉換爲json。創建功能來做到這一點。

function remove_json_keys($array) { 
    foreach ($array as $k => $v) { 
    if (is_array($v)) { 
     $array[$k] = $this->remove_json_keys($v); 
    } //if 
    } //foreach 
    return $this->sort_numeric_keys($array); 
} 

function sort_numeric_keys($array) { 
    $i=0; 
    foreach($array as $k => $v) { 
     if(is_int($k)) { 
      $rtn[$i] = $v; 
      $i++; 
     } else { 
      $rtn[$k] = $v; 
     } //if 
    } //foreach 
    return $rtn; 
}