Kelvin Kelvin - 4 months ago 13
PHP Question

php session multidimensional array

$_SESSION['items_' . $restaurant_id]["menu_0"] = array(
order_id" => $order_id,
'user_order_id' => $last_order["user_order_id"],
"menu_id" => $menu_id,
"qty" => $qty,
);


that code is my session and will be return become this :

["items_250"]=>
array(2) {
["menu_0"]=>
array(3) {
["user_order_id"]=>
string(2) "85"
["menu_id"]=>
array(3) {
[0]=>
string(2) "236"
[1]=>
string(2) "357"
[2]=>
string(2) "232"
}
["qty"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
[2]=>
string(1) "1"
}
}


in my `$menu_id is array :

array(4) {
[0]=>
string(3) "236"
[1]=>
string(3) "357"
[3]=>
string(3) "232"
}


this is my
$qty
:

array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
[2]=>
string(1) "1"
}


i want trying to make my session will be return like this :

["items_250"]=>
array(3) {
["menu_0"]=>
array(3) {
["user_order_id"]=>
string(2) "85"
["menu_id"]=>
string(3) "236"
["qty"]=>
int(1)
}
["menu_1"]=>
array(3) {
["user_order_id"]=>
string(2) "85"
["menu_id"]=>
string(3) "357"
["qty"]=>
int(1)
}
["menu_2"]=>
array(3) {
["user_order_id"]=>
string(2) "85"
["menu_id"]=>
string(3) "232"
["qty"]=>
int(1)
}


guys can you help me how to make my session become like that?

thank you (:

Answer

Just use good ol' for loop. First get the count, then create the necessary rows:

$count = count($menu_id); // get count
for($i = 0; $i < $count; $i++) {
    $_SESSION['items_' . $restaurant_id]['menu_' . $i] = array(
        'user_order_id' => $last_order['user_order_id'],
        'menu_id'       => $menu_id[$i],
        'qty'           => $qty[$i],
    );
}
Comments