Hello I am trying to push associative arrays inside an array. But I can't figure out how to do so. All I managed to do is to push the index without its associated value. Can you guys help me figure this out?
Here's my code :
<?php
$mainshelf = array(
shelf1=> array('apple'=>5, 'banana'=>6, 'lemon'=>7, 'apricot'=>8, 'mango' =>9),
shelf2=> array('salad'=>13, 'tomato'=>12, 'carrot'=>2, 'zuchini'=>15, 'potato' =>20),
shelf3=> array('veal'=>20, 'mutton'=>22, 'chicken'=>19, 'pork'=>25, 'fish' =>17)
);
?>
<?php
session_start();
include 'data.php';
//Generate options in each select
function select($shelf){
foreach($shelf as $key=>$value){
echo "<option>$key</option>";
}
}
// Creating the shopping cart tab
if(!isset($_SESSION['cart'])){
$_SESSION['cart']=[];
}
//Storing items in shopping cart
function listitems($selectshelf){
if(!empty($selectshelf)){
array_push($_SESSION['cart'],$selectshelf);
}
}
// Print out the cart's content
function cartcontent() {
if(!empty($_SESSION['cart']))
foreach($_SESSION['cart'] as $key=>$value){
echo "<p>$value</p>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="php.css">
</head>
<body>
<div id="container_shelf">
<div class="shelf">
<h2>Fruits</h2>
<form action="php1.php" method="post">
<select name="fruits">Fruits
<?php select($mainshelf[shelf1])?>
<?php listitems($_POST['fruits'])?>
</select><br>
<input type="submit" value="Add to cart">
</form>
</div>
<div class="shelf">
<h2>Vegetables</h2>
<form action="php1.php" method="post">
<select name="vegetables">Vegetables
<?php select($mainshelf[shelf2])?>
<?php listitems($_POST['vegetables'])?>
</select><br>
<input type="submit" value="Add to cart">
</form>
</div>
<div class="shelf">
<h2>Meat</h2>
<form action="php1.php" method="post">
<select name="meat">Meat
<?php select($mainshelf[shelf3])?>
<?php listitems($_POST['meat'])?>
</select><br>
<input type="submit" value="Add to cart">
</form>
</div>
</div>
<div id='shopping_cart'>
<h2>Shopping cart</h2>
<?php cartcontent(); echo"<br>"?>
</div>
Another way to "push" something into an array is this:
$_SESSION['cart'][] = $selectshelf;
It will put the content of $selectshelf
in a new element at the end of the array, no matter what its value is.
Here is an example of using arrays as values
$shelf = array(
'book1' => array('title' => 'XYZ', 'pages' => 200),
'book2' => array('title' => 'ABC', 'pages' => 100)
);