2016-12-27 84 views
0

不知道爲什麼這不會轉換,我會認爲它可能與字符串有關,但我得到np輸出。轉換json字符串到php關聯數組

$string = '[{title : "Comp 1 Product",columns : ["Our Vehicle","Features","Their Vehicle"], items : [["dcq","adv","asdvasdv"],["sdv","sdv","sdv"]]},{title : "qwefqw",columns : ["Section 1","Features","Section 2"],items : [["qqwec","qwe","qwegqwev"]]}]'; 

print_r(json_decode($string), true); 

任何幫助,將不勝感激!

+2

這不是有效的JSON。在JSON中,屬性名稱需要用雙引號。 – Barmar

+1

那個字符串從哪裏來的?您需要修復源代碼,以便它能夠正確創建JSON。它應該使用JSON庫,而不是手動構建它。 – Barmar

+1

我已經發布了調試這些問題的方法,並找出問題所在。請在源頭修改。 –

回答

6

如果你看到:

<?php 
    header("Content-type: text/plain"); 
    $string = '[{title : "Comp 1 Product",columns : ["Our Vehicle","Features","Their Vehicle"], items : [["dcq","adv","asdvasdv"],["sdv","sdv","sdv"]]},{title : "qwefqw",columns : ["Section 1","Features","Section 2"],items : [["qqwec","qwe","qwegqwev"]]}]'; 
    print_r(json_decode($string), true); 
    print_r(json_last_error()); 
?> 

上面的代碼返回一個4,這意味着JSON_ERROR_SYNTAX,這是使用JSON語法錯誤。當使用JSON林特選中,您的JSON拋出:

prevoew

你需要糾正它看起來像:

[{ 
    "title": "Comp 1 Product", 
    "columns": ["Our Vehicle", "Features", "Their Vehicle"], 
    "items": [ 
     ["dcq", "adv", "asdvasdv"], 
     ["sdv", "sdv", "sdv"] 
    ] 
}, { 
    "title": "qwefqw", 
    "columns": ["Section 1", "Features", "Section 2"], 
    "items": [ 
     ["qqwec", "qwe", "qwegqwev"] 
    ] 
}] 

你現在有什麼是JavaScript對象,而不是一個有效JSON

+2

我正要發佈這:) :) – Farkie

+0

@Farkie謝謝隊友...':)' –

0

除了無效的json,print_r(json_decode($string), true);什麼都不打印,但返回值。爲了讓打印的輸出結果,你需要:

print_r(json_decode($string)); 

echo print_r(json_decode($string), true); 

前者是更好的。