简体   繁体   中英

PHP Multiple foreach loop to insert object in array

I want to add elements to an array with a condition, but with this code the $ready array only work with the first value of array. what did i miss ?

$data['garduinduk'] :

 Array ( [0] => stdClass Object ( 
            [id] => 1 
            [id_app] => 2 
            [id_basecamp] => 1 
            [nama] => GI BOGOR BARU 
            [room] => 
           ) 
        [1] => stdClass Object ( 
            [id] => 2 
            [id_app] => 2 
            [id_basecamp] => 1 
            [nama] => GI CIAWI BARU 
            [room] => 
          ) 
        [2] => stdClass Object ( 
            [id] => 3 
            [id_app] => 2 
            [id_basecamp] => 1 
            [nama] => GI CIAWI 
            [room] => 
          )

$ready :

Array ( [0] => stdClass Object (
            [lokasi] => 1 
            [berlaku_dari] => 
            [berlaku_sampai] => 0000-00-00 
            [status] => On_progress 
            [file] => 
           ) 
        [1] => stdClass Object ( 
            [lokasi] => 16 
            [berlaku_dari] => 
            [berlaku_sampai] => 0000-00-00 
            [status] => On_progress 
            [file] => 
           ) 
        [2] => stdClass Object ( 
            [lokasi] => 2 
            [berlaku_dari] => 
            [berlaku_sampai] => 0000-00-00 
            [status] => On_progress 
            [file] => /assets/files/155bd035e88358b.PNG
           ) 
        [3] => stdClass Object ( 
            [lokasi] => 2 
            [berlaku_dari] => 2019-02-27 
            [berlaku_sampai] => 2019-02-28 
            [status] => Selesai 
            [file] => /assets/files/215c76691f12ae9.pdf
          ) 
     )

Code :

foreach ($data['garduinduk'] as $key => $gi){
            foreach ($ready as $rdy){
                if ($rdy->lokasi == $gi->id){ 
                    if ($rdy->status == 'On_progress'){
                        $gi->berlaku_dari = 'ON PROGRESS';
                        $gi->berlaku_sampai = 'ON PROGRESS';
                        $gi->file = 'ON PROGRESS';
                    }else{ 
                        $gi->berlaku_dari = $rdy->berlaku_dari;
                        $gi->berlaku_sampai = $rdy->berlaku_sampai;
                        $gi->file = $rdy->file;
                    }

                }else{
                    $gi->berlaku_dari = '';
                    $gi->berlaku_sampai = '';
                    $gi->file = '';
                }
            }
        }

Use reference on $gi

foreach ($data['garduinduk'] as $key => &$gi){

or use

$data['garduinduk'][$key]->

instead of

$gi->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM