2012-08-31 83 views
0

我有一堆值和PHP數組和我需要將其轉換成JSON值用於經由CURL張貼到parse.comPHP json_encode問題

的問題是,PHP數組被轉換成JSON對象(字符串鍵和值,VS字符串只是值)

我結束了

{"showtime":{"Parkne":"1348109940"}} 

而是然後

{"showtime":{Parkne:"1348109940"}} 

解析抱怨說這是一個對象而不是數組,因此不會接受它。

由於

{"showtime":{"Parkne":"1348109940"}} 

是一個JSON對象(key = a string

反正有沒有做到這一點使用json_encode?或者一些解決方案

回答

2

盲注......我的印象是你的PHP數據結構不是你想要開始的那個。你可能有這樣的:

$data = array(
    'showtime' => array(
     'Parkne' => '1348109940' 
    ) 
); 

...並確實需要這樣的:

$data = array(
    array(
     'showtime' => array(
      'Parkne' => '1348109940' 
     ) 
    ) 
); 

隨意編輯的問題,並提供預期輸出的一個樣本。

+0

哇......我簡直不敢相信那很簡單。 – Steven

6

這就是JSON規範:對象鍵必須被引用。雖然你的第一個沒有加引號的版本是有效的Javascript,所以引用的版本,並將在任何JavaScript引擎中解析相同。但是在JSON中,鍵必須被引用。 http://json.org


跟帖:

展示你是如何定義你的陣列,除非你上面的樣品是你的陣列。這一切都歸結於你如何定義你正在編碼的PHP結構。

// plain array with implicit numeric keying 
php > $arr = array('hello', 'there'); 
php > echo json_encode($arr); 
["hello","there"] <--- array 

// array with string keys, aka 'object' in json/javascript 
php > $arr2 = array('hello' => 'there'); 
php > echo json_encode($arr2); 
{"hello":"there"} <-- object 

// array with explicit numeric keying 
php > $arr3 = array(0 => 'hello', 1 => 'there'); 
php > echo json_encode($arr3); 
["hello","there"] <-- array 

// array with mixed implicit/explicit numeric keying 
php > $arr4 = array('hello', 1 => 'there'); 
php > echo json_encode($arr4); 
["hello","there"] <-- array 

// array with mixed numeric/string keying 
php > $arr5 = array('hello' => 'there', 1 => 'foo'); 
php > echo json_encode($arr5); 
{"hello":"there","1":"foo"} <--object 
+0

那麼爲什麼Parse.com抱怨,我向它發送的對象不是一個數組? – Steven

+0

因爲JS中的數組是嚴格數字鍵控的。你發送一個字符串鍵,這使得它成爲一個對象。同樣,'{}'表示JS中的對象。數組使用'[]'。你的'[{}]'註釋示例是一個數組,其中包含一個元素:一個帶鍵值的公園車道/ 111的物體。你是什​​麼意思「不能捲曲」? –

+0

好吧,爲什麼json_encode使用{}編碼我的PHP數組?我怎樣才能使用[]? – Steven

0

可以使用json_encode 您的數組轉換成JSON假設你的數組不爲空,你可以做這樣的

$array=(); 
$json = json_encode($array); 
echo $json; 
0

這聽起來像你需要把你的單個對象和數組中的包裹。

試試這個:

// Generate this however you normally would 
$vals = array('showtime' => array("Parkne" => "1348109940")); 

$o = array(); // Wrap it up ... 
$o[] = $vals; // ... in a regular array 

$post_me = json_encode($o);