Reputation: 23
i wanted to make the output look like this
[{"0":"1.1","1":"KAS & BANK","2":"kosong"},
{"0":"1.1","1":"KAS & BANK","2":"kosong"},
{"0":"1.1","1":"KAS & BANK","2":"kosong"}]
but i really messed up with the code and the output this is my controller
public function coa($id){
$data['listcoa'] = $this->easyway_model->getCoa($id);
$this->load->view('perusahaan_coa', $data);
}
and this is my model
public function getCoa($id)
{
$query = $this->db->select('*')
->from('tb_coa')
->where('id_perusahaan', $id)
->get();
return $query;
}
how should i call it in my view? so far i'm using foreach like this but the output really messed up
foreach($listcoa->result() as $list){
$cabang[] = $list->no_account;
$cabang[] = $list->deskripsi_coa;
$cabang[] = $list->tipe_akun;
$json = json_encode($cabang, JSON_FORCE_OBJECT);
echo $json; }
this is the output i get so far
{"0":"1.1","1":"KAS & BANK","2":"kosong"}{"0":"1.1","1":"KAS & BANK","2":"kosong","3":"1.1.001","4":"KAS","5":"kosong"}{"0":"1.1","1":"KAS & BANK","2":"kosong","3":"1.1.001","4":"KAS","5":"kosong","6":"1.1.002","7":"MANDIRI","8":"kosong"}
without the comma and the index of array keep increasing .
Upvotes: 0
Views: 2894
Reputation: 62074
You firstly need to move
$json = json_encode($cabang, JSON_FORCE_OBJECT);
echo $json;
outside your foreach
loop. At the moment it's executing that command every time your loop runs, so you're outputting the $cabang
array multiple times, and each time it contains more data, as the result of the latest loop is added.
You can also remove the JSON_FORCE_OBJECT setting if you want an array as the output, as per your question. And you need to make $cabang a multi-dimensional array.
$cabang = array();
foreach($listcoa->result() as $list){
$item = array();
$item[0] = $list->no_account;
$item[1] = $list->deskripsi_coa;
$item[2] = $list->tipe_akun;
$cabang[] = $item;
}
$json = json_encode($cabang);
echo $json;
Upvotes: 2