【问题标题】:compare quantity and search in array values比较数量并在数组值中搜索
【发布时间】:2019-04-20 10:55:56
【问题描述】:

当用户输入数量时,我有一个条件逻辑,如果数量为 200,价格将为 4 美元,如果数量为 400,价格将为 4.8 美元,因此如果用户输入 150 作为数量,它将检查哪个是价值匹配,因此它将获得与可用数量匹配的价格,例如用户输入 150 个数量,因此它处于 200 个条件,因此将给出为 200 个数量定义的价格

后端可用的示例条件

 [wholesalePrices] => Array
    (
        [0] => Array
            (
                [quantity] => 10
                [price] => 9.99
            )

        [1] => Array
            (
                [quantity] => 25
                [price] => 8
            )

        [2] => Array
            (
                [quantity] => 50
                [price] => 6
            )

        [3] => Array
            (
                [quantity] => 100
                [price] => 4
            )

我试过用这个,但这对我不起作用

<form>
   <input type="text" name="quantity" placeholder="Quantity" />
   <input type="text" name="price" placeholder="Costing" readonly />
   <input type="submit" name="submit" value="Show Cost" /> 
</form>

$data['wholesalePrices'] = 
    array(
      array('quantity' => 10, 'price' => 9.99),
      array('quantity' => 25, 'price' => 8),
      array('quantity' => 50, 'price' => 6),
      array('quantity' => 100, 'price' => 4)
    );

$qty = $_POST['quantity'];

if(in_array($qty , $data['wholesalePrices'])) {
    echo "price exist";
} else {
    echo "Not Matched";
}

我的英语不太好,所以无法正确解释,如果需要更多解释,请告诉我,希望你们能帮我解决这个问题

【问题讨论】:

  • 您应该检查范围。您正在检查输入值是否在数组中。例如,如果用户键入 60 的数量,则不匹配,因为 60 不在数组中。有50个,有100个,但是所有的中间值都不在数组里。

标签: php arrays search


【解决方案1】:

你可能想试试:

$qty = $_POST['quantity'];

$matched=false;
foreach ($data['wholesalePrices'] as $row)
  if($row['quantity']==$qty) {
    $matched=true;
    break;
  }

if($matched) {
    echo "price exist";
} else {
    echo "Not Matched";
}

foreach 循环的必要性还表明,您的数据结构不是最佳的。

编辑

问题已被编辑为不寻找完全匹配,而是寻找范围匹配 - 仍然不清楚,所以我假设意思是

  • 数量1-10:价格9.99
  • 数量11-25:价格8
  • 数量26-50:价格6
  • 数量51-100:价格4

这会给

$qty = $_POST['quantity'];
//Input sanitization missing: Must be integer >=1

$price=0;
foreach ($data['wholesalePrices'] as $row)
  if($row['quantity']>=$qty) {
     $price=$row['price'];
     break;
  }

if($price>0) {
    echo "price exist";
} else {
    echo "Not Matched";
}

【讨论】:

  • 如果我输入数量为 35 则不工作,它显示不匹配它应该显示此数组值的价格 'quantity' => 50,'price' => 6,因为数量是 35 所以它;s 在 50 qunaityt 范围内
  • 这不是你的问题所说的 - 那么你想要一个完全匹配的。我会调整答案。
猜你喜欢
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
相关资源
最近更新 更多