2013-05-27 21 views
-4

即時嘗試解碼php中的二維數組與json_decode。在多維數組上使用json_decode

創建我的數組是這樣的:

$query3 = 'SELECT * FROM `files` WHERE `company`="'.$_POST['company'].'"'; 
    $result3 = mysql_query($query3); 
    $return_type = "files"; 
    $data_files; 
    while($row3 = mysql_fetch_object($result3)) 
    { 
     $data_files[] .= json_encode(array("cat" => $row3->cat, "name" => $row3->name)); 
    } 

在我的代碼的底部我用這個:

$return = json_encode($data_files); 

我的結果是這樣的:

["{\"cat\":\"3\",\"name\":\"Flyer Vorwerk C-40 11\\\/2013\"}","{\"cat\":\"4\",\"name\":\"Katalog Sommer 2013\"}","{\"cat\":\"5\",\"name\":\"Beutel wechseln\"}","{\"cat\":\"5\",\"name\":\"Teppich sauber kriegen\"}","{\"cat\":\"3\",\"name\":\"Flyer Vorwerk C-70 11\\\/2013\"}"] 

可悲的太多的qutoes,但是當我刪除mysql部分中的第一個json_encode();時,結果看起來像這樣

["Array","Array","Array","Array","Array"] 

我可以用preg_replace()刪除qutoes,但我想知道是否有更好的解決方案。

我真的很感謝你的幫助。

順便說一句,爲我的蹩腳英語sry!

回答

3
$data_files = array(); 
while ($row3 = mysql_fetch_object($result3)) { 
    $data_files[] = array("cat" => $row3->cat, "name" => $row3->name); 
} 
return json_encode($data_files); 

不要對您的值進行雙重編碼!

+0

謝謝你的快速回答!我已經嘗試過了,我的結果看起來像[「陣列」,「陣列」,「陣列」,「陣列」,「陣列」] –

+0

這是不可能的代碼顯示。你到底在做什麼以獲得結果? – deceze

+0

我使用print來顯示它,僅此而已。我只需要以JSON格式查看結果。 –