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

qyzbxkaa  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(248)

假设我有一个购物车,我通过以下代码从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存储在一个数组中,而不是上面这一行。
对于exmaple $cart_ids = [] 如何在php中实现这一点?

erhoui1w

erhoui1w1#

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

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

相关问题