Isnanu Isnanu - 2 months ago 8
PHP Question

How to select use SQL with a row is Array

I have variable array($avail) like this :

$avail =
Array (
[0] => Array
(
[item_id] => 1
[qty_avail] => 44
)

[1] => Array
(
[item_id] => 4
[qty_avail] => 33
)

[2] => Array
(
[item_id] => 6
[qty_avail] => 50
) .....
);


And i want select with codeigniter :

$this->db->select(
'item_id,'
.$avail[0]['qty_avail'].' as "qty_avail",
qty_tocome, qty_togo'
);
$this->db->order_by('item_id', 'asc');
$this->db->where('item_category_id = ', $category_id);
$query = $this->db->get('t_inventory i',$limit,$offset)->result_array();
print_r($query);


The result is all [qty_avail] always $avail[0] :

Array (
[0] => Array
(
[item_id] => 1
[qty_avail] => 44
[qty_tocome] => 0.00
[qty_togo] => 0.00
)

[1] => Array
(
[item_id] => 4
[qty_avail] => 44
[qty_tocome] => 0.00
[qty_togo] => 0.00
)

[2] => Array
(
[item_id] => 6
[qty_avail] => 44
[qty_tocome] => 0.00
[qty_togo] => 0.00
)
);


So, How to select with looping $avail[0] = become $avail[$i++] in sql?
and i can get result like :

Array (
[0] => Array
(
[item_id] => 1
[qty_avail] => 44
[qty_tocome] => 0.00
[qty_togo] => 0.00
)

[1] => Array
(
[item_id] => 4
[qty_avail] => 33
[qty_tocome] => 0.00
[qty_togo] => 0.00
)

[2] => Array
(
[item_id] => 6
[qty_avail] => 50
[qty_tocome] => 0.00
[qty_togo] => 0.00
)
);


Thanks..

Answer

You can use array_replace_recursive like this:

<?php
$arr = [
    ["item_id" => 1,
    "qty_tocome" => 0.00,
    "qty_togo" => 0.00],
    ["item_id" => 4,
    "qty_tocome" => 0.00,
    "qty_togo" => 0.00],
    ["item_id" => 6,
    "qty_tocome" => 0.00,
    "qty_togo" => 0.00]
];

$avail = [
["qty_avail" => 44],
["qty_avail" => 33],
["qty_avail" => 50]
];

$finalArr = array_replace_recursive($arr,$avail);
print_r($finalArr);

So your output will be:

Array
(
    [0] => Array
        (
            [item_id] => 1
            [qty_tocome] => 0
            [qty_togo] => 0
            [qty_avail] => 44
        )

    [1] => Array
        (
            [item_id] => 4
            [qty_tocome] => 0
            [qty_togo] => 0
            [qty_avail] => 33
        )

    [2] => Array
        (
            [item_id] => 6
            [qty_tocome] => 0
            [qty_togo] => 0
            [qty_avail] => 50
        )

)

But make sure that the quantity gets assigned in the right order, since you are using $this->db->order_by('item_id', 'asc');.