简体   繁体   English

在PHP中向数据库添加多维数组

[英]Adding multi dimensional array to database in PHP

Array ( [0] => Array ( [0] => Array ( [name] => Heart Choclates [code] => LFB-P-10 [qty] => 1 [type] => main [price] => 1200 [stock] => 5 [image] => choclates-valentines-day.jpg [quantity] => 12 [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [1] => Array ( [name] => Birthday Pink [code] => KB-P-5 [qty] => 1 [type] => addon [price] => 600 [stock] => 7 [image] => pink-roses.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) ) [1] => Array ( [0] => Array ( [name] => Red & Yellow Roses [code] => KB-P-6 [qty] => 1 [type] => main [price] => 800 [stock] => 9 [image] => birthday-red-roses.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [1] => Array ( [name] => Signature Cake [code] => KB-P-7 [qty] => 1 [type] => addon [price] => 0 [stock] => 9 [image] => signature-cake.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [2] => Array ( [name] => Truffle Cake [code] => KB-P-8 [qty] => 1 [type] => addon [price] => 10 [stock] => 7 [image] => truffle-cake.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) ) )

I have an array like this.. an array of orders and array of products inside each array of orders. 我有一个像这样的数组..每个订单数组中都有一个订单数组和一个产品数组。 Now i need to add these arrays into database with orders in each row and products seprated by a <br/> . 现在,我需要将这些数组添加到数据库中,并在每行中添加订单,并用<br/>分隔产品。 How is it possible? 这怎么可能? Thanks in advance. 提前致谢。

I used this for each to print the code. 我用它来打印代码。

<?php
    session_start();
    error_reporting(0);
    print_r($_SESSION["products"]);
    foreach($_SESSION["products"] as $row => $temp){    
?>                                        
<div>
<?php
   foreach($temp as $innerRow => $cart_itm){
    ?>
        <div><?php echo $cart_itm['code']; ?></div>
    <?php
    }
    ?>
</div>
<?php
}
?> 

Expecting this Result 期待这个结果

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

Try this sample code. 试试这个示例代码。

    $orderList[1001] = array(
        0 => array(
                'name' => 'Heart Choclates',
                'code' => 'LFB-P-10',
                'qty' => 1,
                'type' => 'main',
                'price' => 1200,
                'stock' => 5,
                'image' => 'choclates-valentines-day.jpg',
                'quantity' => 12,
                'expdate' => 'May 27th 2017',
                'exptime' => '11:00 PM to 12:00 AM',
                'expdtype' => 'Mid night delivery'
            ),
        1 => array(
                'name' => 'Birthday Pink',
                'code' => 'KB-P-5',
                'qty' => 1,
                'type' => 'addon',
                'price' => 600,
                'stock' => 7,
                'image' => 'pink-roses.jpg',
                'quantity' => 3,
                'expdate' => 'May 27th 2017',
                'exptime' => '11:00 PM to 12:00 AM',
                'expdtype' => 'Mid night delivery'
            )
    );

$orderList[1002] = array(
        0 => array(
                'name' => 'Red & Yellow Roses',
                'code' => 'KB-P-6',
                'qty' => 1,
                'type' => 'main',
                'price' => 800,
                'stock' => 9,
                'image' => 'birthday-red-roses.jpg',
                'quantity' => 10,
                'expdate' => 'May 27th 2017',
                'exptime' => '11:00 PM to 12:00 AM',
                'expdtype' => 'Mid night delivery'
            )
    );


echo '<pre>';
print_r($orderList);
echo '<pre>';

$productList = array();

foreach ($orderList as $key => $value)
{
    $names = array();
    $quantity = array();

    foreach ($value as $key1 => $value1)
    {
        $names[] = $value1['name'];
        $quantity[] = $value1['quantity'];
    }

    $productList[$key]['names'] = implode('<br>', $names);  // Used `:` insted of '<br>' for separator. But, You can use whatever you want. But, better don't use any HTML tag.
    $productList[$key]['quantity'] = implode('<br>', $quantity);
}

echo '<pre>';
print_r($productList);
echo '<pre>';


// Sample DATA INSERTION Query by PDO
try {
    $conn = new PDO('mysql:host=localhost;dbproductName=someDatabase', $userproductName, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare the query ONCE
    $stmt = $conn->prepare('INSERT INTO someTable VALUES(:name, :quantity)');

    foreach ($productList as $key => $value) {
        $productName = $value['names'];
        $productQuantity = $value['quantity'];

        $stmt->bindParam(':name', $productName);
        $stmt->bindParam(':quantity', $productQuantity);

        $stmt->execute();
    }

} catch(PDOException $e) {
    echo $e->getMessage();
}

// Ref : https://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338

I hope this will get you started: 我希望这可以帮助您入门:

$data = array(
    array(
        array(
            'name'  => 'Heart Choclates',
            'code'  => 'LFB-P-10',
            'qty'   => '1' 
        ),
        array(
            'name'  => 'Birthday Pink',
            'code'  => 'KB-P-5',
            'qty'   => '1' 
        )
    ),
    array(
        array(
            'name'  => 'Red & Yellow Roses',
            'code'  => 'KB-P-6',
            'qty'   => '1'
        ),
        array(
            'name'  => 'Signature Cake',
            'code'  => 'KB-P-7',
            'qty'   => '1'
        ),
        array(
            'name'  => 'Truffle Cake',
            'code'  => 'KB-P-8',
            'qty'   => '1'
        )
    )
);

foreach( $data as $row_item )
{
    $row = array();

    foreach( $row_item as $product )
    {
        foreach( $product as $key => $value )   
        {
            if( isset( $row[ $key ] ) )
                $row[ $key ] .= $value . ' <br> ';
            else
                $row[ $key ] = $value . ' <br> ';        
        }
    }

    //--- 
    echo 'Row: <br>';
    var_dump( $row );
    echo '<br><br>';

    //-- insert the contents of $row array into the database
}

Output: 输出:

在此处输入图片说明

You can insert the contents of $row array into database. 您可以将$row数组的内容插入数据库。


EDIT 编辑

Please note that, the above answer is based on your specific question that you asked. 请注意,以上答案基于您所提出的特定问题。

I still didn't understood what exactly you are doing here. 我仍然不明白您在这里到底在做什么。 If you are trying to store the details of an order, then this is a poor method of accomplishing it! 如果您要存储订单的详细信息,那么这是完成订单的一种糟糕方法! You should keep separate database table and use a relationship to join together. 您应该保留单独的数据库表,并使用关系来联接在一起。 This is what a relational database is for! 这就是关系数据库的作用!

For example, let the two tables be tblOrderMaster and tblOrderDetails . 例如,让两个表为tblOrderMastertblOrderDetails

Here, in the tblOrderMaster table, the primary key will be the order_id and you would probably gonna store the total amount, discount amount, total service tax, order date, customer id, order status, etc. 在这里,在tblOrderMaster表中,主键将是order_id ,您可能会存储总金额,折扣金额,总服务税,订单日期,客户ID,订单状态等。

And in the tblOrderDetails table, you are gonna have several rows, in which we are gonna store each products of a particular order. tblOrderDetails表中,您将有几行,我们将在其中存储特定订单的每个产品。 For example, it will store order id (foreign key), product id, unit price, quantity, tax, total (unit_price x quantity), etc.. 例如,它将存储订单ID(外键),产品ID,单价,数量,税金,总计(单价x数量)等。

This would be the proper way, I believe. 我相信这是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM