2016-08-01 127 views
3

我有一個JSON數組像吹:如何解析這種JSON數組的

{ 
    "0": { 
     "kind": "mammal", 
     "name": "Pussy the Cat", 
     "weight": "12kg", 
     "age": "5" 
    }, 
    "1": { 
     "kind": "mammal", 
     "name": "Roxy the Dog", 
     "weight": "25kg", 
     "age": "8" 
    }, 
    "2": { 
     "kind": "fish", 
     "name": "Piranha the Fish", 
     "weight": "1kg", 
     "age": "1" 
    }, 
    "3": { 
     "kind": "bird", 
     "name": "Einstein the Parrot", 
     "weight": "0.5kg", 
     "age": "4" 
    } 
} 

我刪除的元素「食人魚魚」隨着(未設置)我的JSON代碼改變吹:

{ 
    "0": { 
     "kind": "mammal", 
     "name": "Pussy the Cat", 
     "weight": "12kg", 
     "age": "5" 
    }, 
    "1": { 
     "kind": "mammal", 
     "name": "Roxy the Dog", 
     "weight": "25kg", 
     "age": "8" 
    }, 
    "3": { 
     "kind": "bird", 
     "name": "Einstein the Parrot", 
     "weight": "0.5kg", 
     "age": "4" 
    } 
} 

當我刪除元素的元素變化的計數器0,1,3 所以現在我不能在我的JSON元素完全訪問

我想這個代碼回聲值:

for ($i = 0; $i < $JsonCount - 1; $i++) { 
    echo "Name :"; 
    echo $json_cod[$i]['name']; 
    echo "<br/>"; 
    echo "Age :"; 
    echo $json_cod[$i]['age']; 
    echo "<br/>"; 
} 

出認沽:

Name :Pussy the Cat 
Age :5 
Name :Roxy the Dog 
Age :8 
+0

http://php.net/manual/en/control-structures.foreach.php – wazelin

+1

你的數據結構看起來並不像一個JSON陣列。你確定這就是你想要解析的嗎? –

+1

http://php.net/manual/en/function.array-values.php –

回答

2

嘗試使用foreach

foreach ($json_cod as $item) { 
    echo "Name :";echo $item['name'];echo "<br/>"; 
    echo "Age :";echo $item['age'];echo "<br/>"; 
} 
0

如果你想用你的代碼呼應,從陣列中使用$newarray=array_values($oldarray)刪除值重新索引後陣。

0

這是因爲unset()從數組中刪除鍵值/索引值並保持原樣,即不重新排列鍵/索引。

如果要重新排列密鑰,請使用array_slice(),而不要參見array_slice。你會得到你想要的。你將能夠做到

for($i=0; $i <$JsonCount-1 ; $i++) 
{ 
    echo "Name :";echo $json_cod[$i]['name'];echo "<br/>"; 
    echo "Age :";echo $json_cod[$i]['age'];echo "<br/>"; 
}