【问题标题】:Nested JSON Object Looping in PHP CodeigniterPHP Codeigniter 中的嵌套 JSON 对象循环
【发布时间】:2019-01-29 15:31:22
【问题描述】:

我在从 Controller 创建嵌套对象循环时遇到问题。 这是我目前正在使用的数据

我已经尝试过的是:

function getCoordinate() {

 // Distict SQL Query for first loop 
     (SELECT DISTINCT(id_shipment) as id_shipment FROM tbl_tracking)

    $id_shipment = $this->Maps_model->getIdShipment(); 

 // First Loop
      foreach ($id_shipment as $value) {
          // The object i want to loop for views
          $json = array(
                    'type' => 'Feature',
                    'properties' => json_decode('{}'),
                    'geometry' => array(
                    'type' => 'LineString',
                    'coordinates' => array()
                  ));

 //Query for getting coordinate
   (SELECT a.latitude,a.latitude,b.ship_name from tbl_tracking a
    LEFT JOIN tbl_shipment b on a.id_shipment = b.id
    WHERE a.id_shipment = $value['id_shipment']);

      $coordinate = $this->Maps_model->getCoordinate($value['id_shipment']);

 //Second Loop inside The First Loop
        foreach ($coordinate as $key) {
          $json['geometry']['coordinates'] = array (  
                (float)$key['latitude'],
                (float)$key['longitude']
          );
        }
    echo json_encode($json);
    }
}

上面提供的代码没有生成 JSON Object 。 如何生成正确的循环来生成 JSON 对象?

【问题讨论】:

    标签: php sql json codeigniter object


    【解决方案1】:

    您没有提供太多信息,但尝试做这样的事情。

    function getCoordinate()
    {
    
        /* ... */
        $coordinates = [];
    
        // Second Loop inside The First Loop
    
        foreach($coordinate as $key) {
          /* ************* */
          // note the "[]" to add new items
          /* ************* */
          $coordinates[] = array(
            (float)$key['latitude'],
            (float)$key['longitude']
          );
        }
        $json['coordinates'] = $coordinates;
        echo json_encode($json);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 2016-11-17
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多