我想检查
$stock
中的每个值是否都高于$request
中具有相同索引的值。
$stock = array("7", "5", "3");
$request = array("3", "6", "3");
在这种情况下,第二个
$request
值高于库存值(6 比 5)——因此库存不足。
如何检查
$request
中是否有任何值高于 $stock
中的相应值?
简单地循环数组并比较各个数组中的索引。由于它的长度总是固定的,因此不需要任何复杂的检查或处理。这假设键是由 PHP 分配的,因此它们都从 0 开始并始终增加 1。
$stock = array("7", "5", "3");
$request = array("3", "6", "3");
var_dump(validate_order($stock, $request)); // false
$stock = array("7", "5", "3");
$request = array("3", "4", "3");
var_dump(validate_order($stock, $request)); // true
function validate_order($stock, $request) {
foreach ($stock as $key=>$value) // Fixed length, loop through
if ($value < $request[$key])
return false; // Return false only if the stock is less than the request
return true; // If all indexes are higher in stock than request, return true
}
由于此函数返回布尔值 true/false,因此只需在
if
语句中使用它,如下所示
if (validate_order($stock, $request)) {
/* Put your code here */
/* The order is valid */
} else {
/* Order is not valid */
}
function checkOrder($stock,$request){
for($i=0; $i < count($stock); $i++){
if($stock[$i] < $request[$i]) return false;
}
return true;
}
PHP8.4 的新验证和搜索功能非常适合此任务,因为它们允许开发人员享受条件中断循环的性能,而不必放弃函数式编码。
由于回调中可以获得每个迭代元素的值和索引,因此条件返回值可以专门针对请求数组中的相关值。 演示
$stock = ["7", "5", "3"];
$request = ["3", "6", "3"];
echo "Are there any items with insufficient stock: ";
var_export(
array_any(
$stock,
fn($v, $i) => $v < $request[$i]
)
);
echo "\n---\nDo all items have sufficient stock: ";
var_export(
array_all(
$stock,
fn($v, $i) => $v >= $request[$i]
)
);
echo "\n---\nWhich stock item value is insufficient: ";
// more helpful if $v was a row from a 2d array
var_export(
array_find(
$stock,
fn($v, $i) => $v < $request[$i]
)
);
echo "\n---\nWhich stock indexes have an insufficient amount: ";
var_export(
array_find_key(
$stock,
fn($v, $i) => $v < $request[$i]
)
);
输出:
Are there any items with insufficient stock: true
---
Do all items have sufficient stock: false
---
Which stock item value is insufficient: '5'
---
Which stock indexes have an insufficient amount: 1