Adem Natural
Adem Natural

Reputation: 105

foreach function not work on CodeIgniter

I have problems in function foreach, the resulting data is not showing all

data form database like below table names is "view_kebutuhan_perjal' : enter image description here Code In Model

function getPerjal()
    {
        $query=$this->db->query("SELECT * from view_kebutuhan_perjal");
        return $query;
    }

Code In Controller :

$Kebutuhan=$this->M_Kebutuhan_Perjal->getPerjal();
foreach ($Kebutuhan->result() as $row ) {
        $hasil=array(
            $row->id_perjal,
            $row->jenis_perjal,
            $row->ruas_jalan,
            $row->lokasi_km,
            $row->letak,
            $row->kondisi,
            $row->tahun,
            $row->tahunRPJMD,
            );
    }

    $data=array(
        'data'=> [$hasil],
    );

    $this->output
    ->set_status_header(201)
    ->set_content_type('application/json', 'utf-8')
    ->set_output(json_encode($data, JSON_PRETTY_PRINT))
    ->_display();
    exit;

But Result data just one record like bellow:-

enter image description here

Upvotes: 3

Views: 422

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

You are over-writing $hasil variable again and again inside foreach() loop. That's why only one value is coming.Do like below:-

$hasil  = array(); // create array variable
foreach ($Kebutuhan->result() as $row ) {
        $hasil[]=array(
            $row->id_perjal,
            $row->jenis_perjal,
            $row->ruas_jalan,
            $row->lokasi_km,
            $row->letak,
            $row->kondisi,
            $row->tahun,
            $row->tahunRPJMD,
            ); // assign data to array variable
    }
$data=array(
    'data'=> [$hasil],
);

Upvotes: 2

Related Questions