FewFlyBy FewFlyBy - 1 month ago 8
PHP Question

Push Array inside an Array PHP

I have a simple query that looks for the same id inside the

$_SESSION['cart_items']
keys. This is the output:

enter image description here

and the code:

$statement = $conn->query("SELECT * FROM product WHERE id IN (".implode(',',array_keys($_SESSION['cart_items'])).")");

$data = array();

while($row = $statement->fetch()) {
$data[] = $row;
}
print_r($data);


This works fine but I want to add a 5th element inside the array. The value will be coming from the value of the associative array
$_SESSION['cart_items'][$row['id']]
inside the while loop. So far what I did:

while($row = $statement->fetch()) {
$data[] = $row;
if(array_key_exists($row['id'], $_SESSION['cart_items']))
{
$another = $_SESSION['cart_items'][$row['id']];
array_push($data, $another);
}
}
print_r($data);


But I get this output:

enter image description here

As you can see, there is an additional
[1]=>23
and
[3]=>47
but that's not what I want to happen. What I want to happen is something like this:

enter image description here

I want it to be a part of the array inside an array. Or more like the 5th element. Can I do something like this?

Answer

try this and tell me if it working for you !

while($row = $statement->fetch()) {

    if(array_key_exists($row['id'], $_SESSION['cart_items']))
    {
        $another = $_SESSION['cart_items'][$row['id']];
        array_push($row, $another);
    }
    $data[] = $row;
}

print_r($data);

For your second question try this and let me know

 while($row = $statement->fetch()) {

if(array_key_exists($row['id'], $_SESSION['cart_items']))
{
    $another = $_SESSION['cart_items'][$row['id']];

    $new_row = $row+array("YOUR_TEXT" => $another);

}
$data[] = $new_row;

} print_r($data);