PHP Multiple foreach循环将对象插入数组

时间:2019-02-27 15:10:42

标签: php arrays

我想向条件中的数组添加元素,但是使用此代码,$ready array仅适用于array的第一个值。我想念什么?

$ 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] => 
          )

$就绪:

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
          ) 
     )

代码:

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 = '';
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

$gi上使用参考

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

或使用

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

代替

$gi->