1

您好我正在尝试使用 in_array,我认为我的语法是正确的,但它显示“第二个参数的数据类型错误”

我的代码是

$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");

while($row = mysqli_fetch_array($result))
    {
    if (in_array($row['ProductID'], $filter))
        {
        }
    }

我的想法是找出 Products Table 中的 ProductID 是否在 Order Table 中。

有人可以帮助我吗,谢谢:-)

4

2 回答 2

3

$filter不是数组;这是一个mysqli_result对象:

$filter = mysqli_query($con, "SELECT ProductID FROM Orders");

我认为您想对其进行迭代,将每个添加ProductID到一个新数组中,然后将该数组传递给in_array函数,如下所示:

$filter = mysqli_query($con, "SELECT ProductID FROM Orders");

$product_ids = array();

while ($row = $filter->fetch_assoc())
{
    $product_ids[] = $row['ProductID'];
}

$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");

while($row = mysqli_fetch_array($result))
{

    if (in_array($row['ProductID'], $product_ids))
    {

    }

}
于 2013-03-30T22:44:22.830 回答
3

您的代码失败,因为$filter是 MySQLi 结果资源,而不是数组。实际上,这最好通过两个表之间的简单内部连接来完成。如果 aProductID中不存在Orders,则INNER JOIN首先将其从结果集中排除。

$sql = "
SELECT Products.* 
FROM
  Products
  INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";

$result = mysqli_query($con, $sql);
if ($result) {
  $results = array();
  while ($row = mysqli_fetch_array($result)) {
    $results[] = $row;
  }
}
// Now $results is a 2D array of all your Products

相反,如果您想检索所有Products并且只是指示它是否具有活动订单,请使用 aLEFT JOIN并测试列表Orders.ProductID中是否为空SELECT

$sql = "
SELECT
  Products.* ,
  /* No orders will print 'no-orders' in a pseudo column called has_orders */
  CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
  Products
  LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";

$result = mysqli_query($con, $sql);
if ($result) {
  $results = array();
  while ($row = mysqli_fetch_array($result)) {
    $results[] = $row;
  }
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...

在这种情况下,您可以在行集上循环测试它是否有订单:

foreach ($results as $r) {
  if ($r['has_orders'] == 'has-orders') {
    // this has orders
  }
  else {
    // it doesn't...
  }
}
于 2013-03-30T22:44:25.720 回答