Skip to content
Advertisement

how to push data object to array of object in php

i have data array nested in hire , how to push new value to array [‘data’] ? The data I have is an object and I want to insert the data into each array

[
        {   
            "divisi" : 01,
            "data": [
                {
                    "status": "MUNDUR",
                    "total": "0"
                }
            ]
        },
        {   
            "divisi" : 02,
            "data": [
                {
                    "status": "BATAL",
                    "total": "0"
                }
            ]
        },
        {...},
        {...},
    ]

result

{   
  "divisi" : 01,
  "data": [
            {
             "status": "BATAL",
             "total": "0"
            },
            {
             "status": "WIN", // new push
             "total": "0"
            }
          ]
},

AND this my code

public function detail_get(){
        $divisi = $this->M_model->db_tbl_divisi();
        $data =array();
        foreach ($divisi as $row){
            $i = $this->M_model->db_realisasi_divisi($row['divisi_kode']);
            $win = $this->M_model->db_win_win($row['divisi_kode'],'win'); // how to push ?
            $data[] = array(
                'divisi' => $row['kode'], // 01,02
                'data' => $i
            );
        }
        $response =  $this->set_response($data,200);
    }

i have code

$win = $this->M_model->db_win_win($row['divisi_kode'],'win'); 

value object 
{
 "status": "win",
 "total": "1"
}

I have a data object that I want to insert into [‘data’] How to do it

Advertisement

Answer

I assume $i is array of arrays, so do array_push($i, $win) (or $i[] = $win)

    public function detail_get() {
        $divisi = $this->M_model->db_tbl_divisi();
        $data = [];
        foreach ($divisi as $row){
            $i = $this->M_model->db_realisasi_divisi($row['divisi_kode']);
            $i[] = $this->M_model->db_win_win($row['divisi_kode'], 'win');

            $data[] = [
                'divisi' => $row['kode'], // 01,02
                'data' => $i,
            ];
        }

        $response = $this->set_response($data,200);
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement