问题
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