简体   繁体   English

PHP基于另一个数组的键创建一个数组

[英]php creating an array based off keys of another array

Background: I have an array created by: 背景:我有一个数组创建者:

$order  = $_POST['order'];

The contents only have a single value per row: 内容每行只有一个值:

[0] => 1
[1] => 4
[2] => 5
[3] => 2
[4] => 2

I am updating a database with this: 我正在用此更新数据库:

for ($i=0; $i<count($order); $i++)
{
$sql = "UPDATE catalog SET quantity=quantity - $order[$i]  WHERE item_number= $i +1";

$result = mysqli_query($connection,$sql) or
die("<b>Query Failed.</b><br>" . mysqli_error($connection));
}

But I would like to use SELECT to search for records in which I have updated. 但是我想使用SELECT来搜索更新后的记录。 Of course the problem is I do not have a direct item number to reference since I used $i +1 to refer to it. 当然问题是我没有直接的项目编号,因为我使用$ i +1来引用它。

As you can see the (array)key+1 to each value is equal to the item_number. 如您所见,每个值的(array)key + 1等于item_number。 So I was hoping to create an array in which the following is true: 所以我希望创建一个满足以下条件的数组:

for ($i=0; $i<count($order); $i++)
{ 
if ($order[$i] > 0)
{
$itemNum[$i] = 1;
} else {
$itemNum[$i] = 0;
}

I am sure I am over thinking this but I just need to be able to set up a WHERE statement displaying only item_num records which were just updated. 我敢肯定,我已经考虑过了,但是我只需要能够建立一个WHERE语句,只显示刚刚更新的item_num记录。

Make an array containing all the item_numbers you are updating. 创建一个包含要更新的所有item_numbers的数组。 Then, select those item_numbers. 然后,选择那些item_numbers。

$updated = [];
for ($i=0; $i<count($order); $i++)
{
  if ($order[$i] > 0) {
    $updated[] = $i + 1;
    $sql = "UPDATE catalog SET quantity=quantity - $order[$i]  WHERE item_number= $i +1";
    $result = mysqli_query($connection,$sql) or
       die("<b>Query Failed.</b><br>" . mysqli_error($connection));
  }
}
$sql = "SELECT * FROM catalog WHERE item_number IN (" . implode(",", $updated) . ")";

What are you going to do if the order is for more quantity than are remaining in catalog? 如果订购的数量大于目录中剩余的数量,该怎么办?

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

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