[英]PHP - Compare 2 values of arrays
I have a question regarding compare two arrays. 我有一个关于比较两个数组的问题。 I already search in this forum but nothing like what I want to achieve.
我已经在这个论坛中搜索了,但是没有什么比我想要达到的要好。
$stock = array("7", "5", "3");
$request = array("3", "6", "3");
What I want to achieve is, if every value in $stock
is higher than $request
, then I can execute the order. 我想要实现的是,如果
$stock
每个值都高于$request
,那么我可以执行订单。 But in this case, request value in position 2 is higher than stock value (6 vs 5). 但是在这种情况下,位置2的请求值高于库存值(6对5)。
My question is, how is the code in PHP to compare if there is any value in $request
is higher than every value in $stock
? 我的问题是,PHP中的代码如何比较
$request
任何值是否高于$stock
每个值? OR to compare if every value in $stock
is higher than every value in $request
? 或比较
$stock
中的每个值是否高于$request
每个值?
Example of my database 我的数据库示例
Thank you in advance. 先感谢您。
Simply loop through the arrays and compare the indexes in the respective arrays. 只需遍历数组并比较各个数组中的索引。 Since it's a fixed length, always, there isn't need for any complex checks or handlings.
由于长度是固定的,因此始终不需要任何复杂的检查或处理。 This assumes that the keys are assigned by PHP, so they all start at 0 and always increase by 1.
假设密钥是由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
}
Since this function returns a boolean, true/false, simply use that in an if
-statement, like this 由于此函数返回一个布尔值,真/假,简单地使用在
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.