Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter replace array values in model

I have been going around in circles with a multidimensional array replace..

I need to replace numbers stored in a DB that relate to a status type.. If I did this in the view it would work but it wont seem to replace in the model?

    function fetch_shipments($orgID){
    $this->db->select('shipID, shipRef, shipCarrier, shipOrigin, shipDestination, shipQty, shipStatus');
    $this->db->where('orgID', $orgID);
    $query = $this->db->get('shipments');

    $result = $query->result_array();

    foreach($result as $row) {
        foreach ($row as $key => $val) {
            $key == 'shipStatus' && $val == 0 ? $val = 'Current' : $val;
            $key == 'shipStatus' && $val == 1 ? $val = 'Pending' : $val;
            $key == 'shipStatus' && $val == 2 ? $val = 'Complete' : $val;
        }
    }

    return $result;
}

Has really left me scratching my head, I know this kind of foreach works as I use it all the time... I feel I am missing something (perhaps obvious) but I just cant put my finger on it. I even tried doing the replace at the object level before outputting an array but couldn't get that to work either.

like image 682
Brian Ramsey Avatar asked Mar 23 '26 04:03

Brian Ramsey


1 Answers

you should save it on your $result variable. not in $val

foreach($result as $k => $row) {
    foreach ($row as $key => $val) {
        $key == 'shipStatus' && $val == 0 ? $result[$k][$key] = 'Current' : $val;
        $key == 'shipStatus' && $val == 1 ? $result[$k][$key] = 'Pending' : $val;
        $key == 'shipStatus' && $val == 2 ? $result[$k][$key] = 'Complete' : $val;
    }
}

return $result;

Or you could remove the inner loop

foreach($result as $k => $row) {
    if($row['shipStatus']==0){
         $result[$k]['shipStatus'] = 'Current';
    }elseif($row['shipStatus']==1){
         $result[$k]['shipStatus'] = 'Pending';
    }else{
         $result[$k]['shipStatus'] = 'Complete';
    }
}

return $result;
like image 175
roullie Avatar answered Mar 24 '26 17:03

roullie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!