Codeigniter,如何以json格式显示选择查询结果?

时间:2016-08-31 03:47:37

标签: php mysql json codeigniter

我有两张桌子 table1: dr_country

enter image description here

table2: dr_city

enter image description here

我必须从两个表中获取数据。我所需的输出应该格式如下:

[{"id":"1","country_name":"Australia","country_code":"61","iso_code":"AUS","city":
[{"id":"1","city_name":"sydney"},{"id":"2","city_name":"melbourne"},{"id":"3","city_name":"perth"},{"id":"4","city_name":"brisbane"}]},
{"id":"2","country_name":"Bangladesh","country_code":"880","iso_code":"BGD","city":
[{"id":"5","city_name":"dhaka"},{"id":"6","city_name":"chittagong"}]}]

我的模型方法如下:

public function countryAction()
{
    $this->db->select("*");
    $this->db->from('dr_country');
    $this->db->join('dr_city', 'dr_country.id = dr_city.country_id','left');

    $result = $this->db->get()->result_array();
   if($result)
   {
        print_r(json_encode($result));

    }
    else
    {
         $detail = array(
            'status'=>'unsucess',   
           );

          echo  json_encode($detail); 
    }
}

它产生如下输出:

[{"id":"1","country_name":"Australia","country_code":"61","iso_code":"AUS","city_name":"sydney","country_id":"1"},{"id":"2","country_name":"Australia","country_code":"61","iso_code":"AUS","city_name":"melbourne","country_id":"1"},{"id":"3","country_name":"Australia","country_code":"61","iso_code":"AUS","city_name":"perth","country_id":"1"},{"id":"4","country_name":"Australia","country_code":"61","iso_code":"AUS","city_name":"brisbane","country_id":"1"},{"id":"5","country_name":"Bangladesh","country_code":"880","iso_code":"BGD","city_name":"dhaka","country_id":"2"},{"id":"6","country_name":"Bangladesh","country_code":"880","iso_code":"BGD","city_name":"chittagong","country_id":"2"}]

因此,为了获得所需的json格式,我应该在模型函数中进行所有更改,我是新手,请提前感谢。

5 个答案:

答案 0 :(得分:0)

请尝试以下步骤:

  1. 获取所有国家/地区 - 从dr_country
  2. 中选择*
  3. 遍历各个国家并获取每个国家/地区的城市

    foreach($ c作为$ c) {   $ countries [$ city_id] =从dr_city中选择*,其中country_id = $ c; }

    1. json encode

答案 1 :(得分:0)

您的预期输出永远不会带有直接数据库。 因为Database在TABLE formate中提供输出。

如果你想要你的预期输出,那么你应该执行2个SQL查询。 i)取国 ii)取城 并创建一个Country Country和一个与Country相关的查找所有城市的foreach循环 并输出数组。

答案 2 :(得分:0)

$countries = $this->db->get('dr_country')->result();
foreach ($countries as $key => $country) {
    $country->city = $this->db->get_where('dr_city', array('country_id' => 
$country->id))->result();
    $countryfinal[]=$country;
}
print_r(json_encode($countryfinal));

答案 3 :(得分:0)

    $countries = $this->db->get('dr_country')->result();
foreach ($countries as $key => $country) {
    $country->city = $this->db->get_where('dr_city', array('country_id' => 
$country->id))->result();
    $countryfinal[]=$country;
}
print_r(json_encode($countryfinal));

答案 4 :(得分:-1)

在你的模特中尝试这个

$countries = $this->db->get('dr_country')->result();
foreach ($countries as $key => $country) {
    $country->city = $this->db->get_where('dr_city', array('country_id' => $country->id))->result();
}
print_r(json_encode($countries));