2016-09-22 46 views
1

我試圖在php數組上使用json_encode。我必須將返回的JSON結構設置爲:數組鍵0而不是僅用於JSON編碼的字符串

[ 
    {"text": "Title1"}, 
    {"text": "URL"} 
] 

我試過了以下內容,但是我始終將0作爲關鍵字。

$xml = simplexml_load_file($url); 

$title1 = $xml->results->result->jobtitle; 
$snippet1 = $xml->results->result->snippet; 
$url1 = $xml->results->result->url; 




$arrays = array('text'=>$title1); 
echo json_encode($arrays); 

我在做什麼錯我的編碼數組?我怎樣才能使它不會返回爲0?

{"text":{"0":"CDL-A Dry Bulk Drivers Wanted - Regional - OH, WV, PA"}} 
+1

您可以附加變量$ url的值? –

+0

你能舉一個XML文件的例子嗎? –

回答

1

請試試這個:你在json_encode沒有錯誤。

$title1 = $xml->results->result->jobtitle; 

...

$arrays = array('text'=>$title1[0]); 
-1

他們的方式要設置你的陣列是不正確。你想要做的是。

$array = [ 
    ['text' => 'hello'], 
    ['text' => 'hello again'], 
]; 

$encoded = json_encode($array); 

print_r($encoded); 

返回

[ 
    {"text":"hello"}, 
    {"text":"hello again"} 
] 
+0

我的錯誤。沒有注意到'jobtitle'以陣列的形式返回,使得Hamid Sardar答案正確無誤。 – SeaFuzz

相關問題