如何在新数组中推送关联数组

时间:2016-01-31 14:22:10

标签: php associative-array

您好我正在尝试在数组中推送关联数组。但我无法弄清楚如何做到这一点。我设法做的就是推送没有相关值的索引。你们能帮我解决这个问题吗?

这是我的代码:

<?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>

2 个答案:

答案 0 :(得分:0)

将某些东西“推”到数组中的另一种方法是:

$_SESSION['cart'][] = $selectshelf;

它会将$selectshelf的内容放在数组末尾的新元素中,无论其值是什么。

答案 1 :(得分:0)

以下是将数组用作值

的示例
$shelf = array(
    'book1' => array('title' => 'XYZ', 'pages' => 200),
    'book2' => array('title' => 'ABC', 'pages' => 100)
);