Php foreach循环和json_encode只返回一个对象Joomla 2.5组件
我目前正在使用Gmaps3为Joomla 2.5制作一个google地图组件,我在地图上填充了标记,但我的foreach循环只返回一个对象 代码如下: My View.json.php:Php foreach循环和json_encode只返回一个对象Joomla 2.5组件,php,jquery,joomla2.5,json,Php,Jquery,Joomla2.5,Json,我目前正在使用Gmaps3为Joomla 2.5制作一个google地图组件,我在地图上填充了标记,但我的foreach循环只返回一个对象 代码如下: My View.json.php: <?php defined( '_JEXEC' ) or die; jimport( 'joomla.application.component.view'); class LocateViewBranches extends JView { public function display($
<?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);
}
}
我已经整理好了你的显示功能。它将以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);
}
我没有测试它,但它应该是您所需要的。我认为您需要将array\u将$response
推送到一个新的数组变量上,然后将json\u encode
改为该数组。是的。。。在循环的每次迭代中,您都会覆盖$response
,而不是添加到循环中。你们会怎么做?
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);
}