如何在数组中存储产品的ID

时间:2018-04-28 08:18:15

标签: php mysql mysqli

假设我有一个购物车,我通过此代码从db获取数据:

$cart_id = $_GET['cart_id'];
$get_add = "SELECT * FROM cart WHERE cart_id = '$cart_id'";
$run_add = mysqli_query($con,$get_add);
$cart_items = [];
$total_price_to_pay = 0;
while ($row_results = mysqli_fetch_array($run_add)){
    $item = array(
        'table_id' => $row_results['table_id'],
        'cart_id' => $row_results['cart_id'],
        'pro_id' => $row_results['product_id'],
        'pro_title' => $row_results['product_title'],
        'pro_price' => $row_results['product_price'],
        'pro_img' => $row_results['product_image'],
        'pro_supplier' => $row_results['product_supplier'],
        'qty' => $row_results['qty'],
        'cart_ip' => $row_results['cart_ip'],
        'pro_total' => $row_results['qty']*$row_results['product_price'],
    );
    $total_price_to_pay +=  $row_results['qty']*$row_results['product_price'];
    $cart_items[] = $item;
}

为了显示结果我做了这个:

    <form method='POST' action=''>
<?php foreach ($cart_items as $cart) {
    echo "<input type='hidden' name='pro_id' value='".$cart['pro_id']."'>
    <h4><a href=''>".$cart['pro_title']."</a></h4>
    <p>".$cart['pro_supplier']."</p>
    <select name='quantites'>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
        <option value='4'>4</option>
        <option value='5'>5</option>
    </select>";
} ?>
    <input name='update' type='submit' value='UPDATE'></input>
</form>

如您所见,我添加了隐藏的输入,其中包含每个产品的ID:

<input type='hidden' name='pro_id' value='".$cart['pro_id']."'>

现在我想将所有产品ID存储在一个数组中,而不是上面这行。

例如$cart_ids = []

我怎么能用PHP做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用array_column()函数获取二维数组中的列数组:

$cart_ids = array_column($cart_items, 'pro_id');