2012-11-20 90 views
0

我目前正在使用Gmaps3,即時在使用標記填充地圖,但我的foreach循環只返回一個對象的點爲Joomla 2.5谷歌地圖組件。下面foreach循環和json_encode只返回一個對象Joomla 2.5組件

代碼:

我View.json.php:

<?php 
defined('_JEXEC') or die; 

jimport('joomla.application.component.view'); 

class LocateViewBranches extends JView 
{ 
    public function display($tpl = null) 
    { 
     $branch = $this->get('Branches'); 

     foreach ($branch as $row) { 
       $response = array(
         'lat' => $row->branch_latitude, 
         'lng' => $row->branch_longitude, 
         'data' => array(), 
        ); 
       $response['data'][] = array(
        'city' => $row->branch_city, 
       ); 

     } 
     echo json_encode($response); 
    } 
} 

,然後在我的模型;

<?php 
defined('_JEXEC') or die; 

jimport('joomla.application.component.model'); 

class LocateModelBranches extends JModel 
{ 
    public function getBranches() 
    { 
     $db = $this->getDbo(); 
     $query = $db->getQuery(true); 

     $query->select('*'); 
     $query->from('#__branches'); 
     $query->where("published = 1"); 

     $db->setQuery($query); 

     $rows = $db->loadObjectList(); 

     return $rows; 
    } 
} 

如果你們需要更多代碼,請大聲呼喊,但我認爲這是兩個關鍵文件。

在此先感謝

+1

我認爲你需要'array_push'將'$ response'放到一個新的數組變量中,而'json_encode'則需要這個數組。 – Blazemonger

+1

是的......你在循環的每次迭代中都覆蓋'$ response',而不是增加它。 – prodigitalson

+0

你們會怎麼做呢? –

回答

1

我整理了您的顯示功能。它會回顯一個json格式的多維數組:

public function display($tpl = null) 
{ 
    $responses = array(); // assign each row to this array 

    $branch = $this->get('Branches'); 
    foreach ($branch as $row) 
    { 
     // append row data to $responses array 
     $responses[] = array(
      'lat' => $row->branch_latitude, 
      'lng' => $row->branch_longitude, 
      'data' => array(
       'city' => $row->branch_city 
      ), 
     ); 
    } 
    echo json_encode($responses); 
} 

我還沒有測試過它,但它應該是你所需要的。

+0

精美的作品謝謝你,哇,救命啊... –

+0

不客氣。 =) – diggersworld