[英]PHP json_encode issue
我有一堆值和一個PHP數組,我需要將其轉換為JSON值,以便通過CURL發布到parse.com
問題是PHP數組轉換為JSON對象(字符串作為鍵和值,而字符串作為值)
我最終
{"showtime":{"Parkne":"1348109940"}}
而不是
{"showtime":{Parkne:"1348109940"}}
並且parse抱怨這是一個對象而不是數組,因此不會接受它。
如
{"showtime":{"Parkne":"1348109940"}}
是JSON對象( key = a string
)
反正有使用json_encode
做到這一點嗎? 還是一些解決方案?
這就是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
盲注...我給您的印象是您的PHP數據結構不是您想開始的。 你可能有這個:
$data = array(
'showtime' => array(
'Parkne' => '1348109940'
)
);
...並且實際上需要這個:
$data = array(
array(
'showtime' => array(
'Parkne' => '1348109940'
)
)
);
隨時編輯問題並提供預期輸出的樣本。
您可以使用json_encode將數組轉換為JSON,前提是您的數組不為空,您可以這樣做
$array=();
$json = json_encode($array);
echo $json;
聽起來您需要將單個對象包裝到數組中。
嘗試這個:
// 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.