2014-02-21 94 views
1

我有兩個不同的陣列如何使用php刪除json_encode中的數組對象索引?

$arr1=Array ('latitude' => 9.9252007, 'longitude' => 78.1197754, 'title' => 'Madurai') ; 
$arr2=Array ('latitude' => 9.2323, 'longitude' => 78.23233, 'title' => 'Peraiyur') ; 

我需要將兩個數組合併成單一的,需要通過json_encode轉換成JSON,所以我的代碼是在這裏給數組合並,並解析成JSON

$obj['markers']=(object) array($arr1, $arr2); 

echo json_encode($obj); 

輸出如下

{"markers": 
{"0":{"latitude":9.9252007,"longitude":78.1197754,"title":"Madurai"}, 
    "1":{"latitude":9.2323,"longitude":78.23233,"title":"Peraiyur"}} } 

,但我需要它像遵循

{"markers":[ 
    { "latitude":9.9252007, "longitude":78.1197754, "title":"Madurai" }, 
    { "latitude":9.2323, "longitude":78.23233, "title":"Peraiyur" } 
]} 

如何刪除它們?

+0

嘿,爲什麼在這裏投票?可以解釋嗎? – kan

+2

爲什麼你要創建'$ new_Arr'然後...無論如何,你可以簡單地嘗試'json_encode(array(「markers」=> array($ arr1,$ arr2)));' – Passerby

+0

+1沒關係;) –

回答

1

爲什麼要鑄造成object?如果你只是刪除(object)鑄造它將完成!

$obj['markers']=array($arr1, $arr2); 

結果:

{"markers":[{"latitude":9.9252007,"longitude":78.1197754,"title":"Madurai"},{"latitude":9.2323,"longitude":78.23233,"title":"Peraiyur"}]} 
1
$obj['markers']=array($arr1, $arr2); 
0

該目的:

{"markers":[ 
    { "latitude":9.9252007, "longitude":78.1197754, "title":"Madurai" }, 
    { "latitude":9.2323, "longitude":78.23233, "title":"Peraiyur" } 
]} 

是相同的:

print_r(json_encode(array('markers' => array($arr1, $arr2)))); 

因此,不需要做任何額外的複雜編碼。

0

試試這個

$arr1=Array ('latitude' => 9.9252007, 'longitude' => 78.1197754, 'title' => 'Madurai') ; 
$arr2=Array ('latitude' => 9.2323, 'longitude' => 78.23233, 'title' => 'Peraiyur') ; 
$obj['markers']=array($arr1, $arr2); 
echo json_encode($obj); 

輸出:

{"markers":[{"latitude":9.9252007,"longitude":78.1197754,"title":"Madurai"},{"latitude":9.2323,"longitude":78.23233,"title":"Peraiyur"}]} 
0

這是怎麼回事必須做到:

$obj['markers']=array(
     array(
     'latitude' => $entity->getLat(), 
     'longitude' => $entity->getLng(), 
     'title' => $entity->getTitle(), 
     ) 
    ); 
$json = json_encode($obj); 
$response = new Response($json); 
$response->headers->set('Content-Type', 'application/json'); 
return $response; 

它會產生這樣的JSON文件:

{"markers":[{"latitude":"36.80610237001900","longitude":"10.17517220741000","title":"Mon annonce"}]}