2016-12-31 63 views
0

我真的不知道如何在對象中變換數組。PHP - 將數組設置爲對象

我需要的是我的陣列可以變成這樣的對象:

var locations= [ 
     {lat: -22.9, lng: -43.23}, 
     {lat: 23.03, lng: 113.12}, 
     {lat: 23.12, lng: 113.25}, 
     {lat: -7.24917, lng: 112.75083}, 
     {lat: -6.323116, lng: 106.870941}, 
     {lat: 40.69, lng: -73.99}, 
     {lat: 40.74, lng: -73.94} 
    ]; 

我使用Ajax檢索數據:

$(function() { 
     $.ajax({ 
      url   : '<?= base_url('admin/getCustomerLatLong'); ?>', 
      method  : 'GET', 
      // dataType : 'JSON', 
      success  : function(data) { 
       console.log(data); 
      }, 
      error: function (jqXHR, textStatus, errorThrown) { 
       alert('Error while getting the data. Call the developer!'); 
      } 
     }); 
    }); 

,我使用笨,這裏是getCustomerLatLong功能我控制器:

public function getCustomerLatLong() { 
    $data = $this->M_customer->getAllCustomers()->result(); 
    $locations = array(); 

    foreach ($data as $location) : 
     $locations['lat'] = $location->latKota; 
     $locations['lng'] = $location->lngKota; 
     echo json_encode($locations); 
    endforeach; 
} 

請任何回答對我有幫助,比ks提前。

回答

3

我想你的問題是由於你在循環中使用echo

試着改變你的控制器是這樣的:

public function getCustomerLatLong() 
{ 
    $data = $this->M_customer->getAllCustomers()->result(); 
    $locations = []; 

    foreach ($data as $location) { 

     $locations[] = [ 
      'lat' => $location->latKota, 
      'lng' => $location->lngKota, 
     ]; 
    } 

    echo json_encode($locations); 

} 

您可能還需要取消註釋dataType : 'JSON',

希望這有助於!

+0

謝謝你,順便問一下你有沒有使用谷歌地圖標記集羣?我根據這些位置設置了所有標記。我嘗試了很多方法,但仍然沒有顯示標記,而且我的控制檯日誌也沒有顯示任何錯誤。 –

+0

我已經很久沒有使用過它們,但是,如果你打開另一個問題,我肯定有人應該能夠幫助:) –