How to prepare a model to return json_encode result ( Codeigniter )

我们两清 提交于 2019-12-25 18:17:40

问题


Here is my Model in Codeigniter with foreach loop in it.

Function.

  public function get_projectcount($qup) {
    echo'[';
    foreach ($qup as $row) {
        $id = $row['myid'];
        $this->db->select('*');
        $this->db->from('projects');
        $this->db->where(array('projects.accountId' => $id));
        $query = $this->db->get();

        $projects_count = count($query->result());
        echo '{"myid":"' . $row['myid'] . '",';
        echo '"total_projects":"' . $projects_count . '"},';
    }
    echo']';
}

I want this as a result of json_encode.


回答1:


You should change your function to:

public function get_projectcount($qup) {
    $result = array();
    foreach ($qup as $row) {
        $id = $row['myid'];
        $this->db->select('*');
        $this->db->from('projects');
        $this->db->where(array('projects.accountId' => $id));
        $query = $this->db->get();

        $projects_count = count($query->result());
        $result[] = array("myid" => $row['myid'], "total_projects" => $projects_count);
    }
    return json_encode($result);
}



回答2:


Try this code:

$data = [];
foreach ($qup as $row) {
    $id = $row['myid'];
    $this->db->select('*');
    $this->db->from('projects');
    $this->db->where(array('projects.accountId' => $id));
    $query = $this->db->get();
    $projects_count = count($query->result());
    array_push($data,array(
             'my_id' => $row['myid'],
             'total_projects' => $projects_count
         )
    );
}
json_encode($data, JSON_PRETTY_PRINT);


来源:https://stackoverflow.com/questions/29230238/how-to-prepare-a-model-to-return-json-encode-result-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!