你好,我試圖推動數組內的關聯數組。但我無法弄清楚如何去做。我所做的只是推動索引而沒有其相關價值。你們能幫我弄清楚嗎?如何推新陣列內的關聯數組
這裏是我的代碼:
<?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>
無法推送鍵/值對的關聯數組的一個例子。相反,您可以'$ SESSION ['cart'] [$ selectShelf] = $ mainshelf [$ selectShelf]'。順便說一句,'$ mainshelf [shelf1]'是無效的語法 - 它應該是'$ mainshelf ['shelf1']'。 – Kenney
我的代碼應該放在哪裏? –
你會這樣做,而不是'array_push'(在'listitems'內) - 但你需要添加一個'global $ mainshelf;' – Kenney