Alaa Al Adnani
Alaa Al Adnani

Reputation: 57

Remove row from array result from codeigniter query

I am executing below query in codeigniter which returns 4 rows:

$available_rooms = $this->db->query("SELECT id_room as id, ea_rooms.name as name FROM ea_rooms_services WHERE id_service =" . $service_id)->result_array();

Output e.g.:

 {
{id:1, name:a}
{id:2, name:b}
{id:3, name:c}
{id:4, name:d}
}

I have an array with room ids $occupiedRooms (e.g. {0=>1, 1=>2}) which is being populated as follows:

$occupiedRooms = array();

foreach ($listing as $element){
... SOMECODE
    if ($id_room != null)
         $occupiedRooms[] = $id_room;
}

I want to unset all rows in $available_rooms that have the same ids in $occupiedRooms.

Expected output:

 {
{id:3, name:c}
{id:4, name:d}
}

I am using below code but it is not working

foreach ($available_rooms as $elementKey => $element){
    if(in_array($element['id'], $occupiedRooms)){
       unset($available_rooms[$elementKey]);
    }
}

I also tried array_filter with below code but it also didn't work:

foreach ($occupiedRooms as $id){
    $available_rooms = array_filter($available_rooms, function($room) use($id)
        {
             return $room['id'] != $id;
        });
}

Upvotes: 0

Views: 318

Answers (1)

db1975
db1975

Reputation: 775

this would be shorter:

$occupied_rooms = array(1,5,6);

$available_rooms = $this->db->query("SELECT id_room as id, ea_rooms.name as name FROM ea_rooms_services WHERE id_service =" . $service_id . " AND id_room NOT IN ( " . implode(",", $occupied_rooms) . " ) ")->result_array();

Upvotes: 2

Related Questions