PHP查询结果中的引用数组值

时间:2014-06-05 04:40:34

标签: php codeigniter geojson

我正在尝试创建一个geoJSON数组,但是我很难访问查询结果中的值。当我通过硬编码"坐标"来测试我的功能时价值观' 2'和' 4'一切正常。

然而,当我尝试设置"坐标"通过引用$row['v2_lat']$row['v2_lng'],这会导致错误。这是PHP代码:

function getGeoJSON2(){
$m = $this->input->POST('municipality');
$l  = $this->input->POST('saleslimit'); 
$q = $this->db->query("SELECT RollNum, Address, v2_lat, v2_lng FROM tblontario WHERE Municipality = '".$m."'"." LIMIT ".$l);    
$res = $q->result();

if(!empty($res)){
    $geoArr = Array(
         "type" => "MultiPoint",
         "coordinates" => Array()
    );  
    foreach ($q->result() as $row) {
      //$geoArr["coordinates"][] = Array(2,4);
        $geoArr["coordinates"][] = Array($row['v2_lat'],$row['v2_lng']);        
    }
    $geoJSON = json_encode($geoArr);
    echo $geoJSON;
 } else {
     echo "{}";
 }
}   

以下是查询结果的示例,并在应用json_encode之后:

[
{
    "RollNum": "193601001000100",
    "Address": "12 STEELES AVE E",
    "v2_lat": "43.8561002",
    "v2_lng": "-79.3370188"
},
{
    "RollNum": "193601001000400",
    "Address": "18 STEELES AVE E",
    "v2_lat": "43.7986849",
    "v2_lng": "-79.4178564"
},
{
    "RollNum": "193601001002100",
    "Address": "36 STEELES AVE E",
    "v2_lat": "43.7987492",
    "v2_lng": "-79.4169781"
}
]

我不明白为什么我似乎无法访问$row['v2_lat']循环中的$row['v2_lng']foreach值。有任何想法吗?感谢。

编辑:我想看到$res变量,这是从查询中返回的数组的格式:

Array
(
[0] => stdClass Object
    (
        [RollNum] => 180501000100100
        [Address] => 2 HILEY AVE
        [v2_lat] => 43.8526509
        [v2_lng] => -79.0499877
    )

[1] => stdClass Object
    (
        [RollNum] => 180501000100200
        [Address] => 4 HILEY AVE
        [v2_lat] => 43.8526678
        [v2_lng] => -79.0501957
    )

[2] => stdClass Object
    (
        [RollNum] => 180501000100300
        [Address] => 6 HILEY AVE
        [v2_lat] => 43.8526848
        [v2_lng] => -79.0504037
    )
)

最后两个结果之间差异的意义是什么?

1 个答案:

答案 0 :(得分:2)

您可以像访问它一样访问它:

$lat = $row->v2_lat; //and not like $row['v2_lat']

或者,如果您想像简单数组一样访问它,则需要更改以下行:

//$res = $q->result(); //this produces objects
$res = $q->result_array();  //this produces array

这将为您生成一个结果数组,您也可以使用之前的代码。