这是我在Codeigniter中使用foreach循环的模型。
功能
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']';
}
我希望这是json_encode的结果。
答案 0 :(得分:3)
您应该将功能更改为:
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);
}
答案 1 :(得分:0)
尝试此代码:
$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);