比较 PHP 中具有相同键的数组值
Compare array values with same key in PHP
我正在尝试比较具有相同键的 2 个数组的值,看看具有相同键的数组的值是否大于另一个。这是数组:
Array
(
[3203] => 2
[7276] => 1
)
Array
(
[3203] => 1
[7276] => 1
)
上面生成数组的代码部分:
foreach ($this->request->post['quantity'] as $key => $value)
{
$cart_value[$key] = $value;
}
foreach ($this->session->data['cart'] as $id => $val) {
$stock[$id] = $this->cart->availableStock($id);
}
如何比较每个键的值?
我有这个 if else 语句:
if ($cart_value > $stock) {
// do something<br>
} elseif ($cart_value = $stock) {
// do another thing
} else {
// do this thing
}
感谢您的帮助。
用array_intersect_assoc on the arrays and then use count看结果是否一样大
或者,使用 array_diff_assoc 并查看结果是否为空。
一切都取决于你想对结果做什么。第一个选项将 return 包含匹配元素的数组,第二个选项将 return 包含不匹配元素的数组。
如果您希望结果基于特定公式(例如 return 只有第二个数组中值较大的项目),您可以使用 array_uintersect_assoc
您可以嵌套 foreach 循环。
foreach ($array1 as $k1 => $v1) {
foreach {$array2 as $k2 => $v2) {
if ($k1 === $k2) {
switch (true) {
case ($v1 < $v2):
// less than
break;
case ($v1 > $v2):
// more than
break;
case ($v1 == $v2):
// equal
break;
default:
// values cannot be compared
break;
}
}
}
}
我正在尝试比较具有相同键的 2 个数组的值,看看具有相同键的数组的值是否大于另一个。这是数组:
Array
(
[3203] => 2
[7276] => 1
)
Array
(
[3203] => 1
[7276] => 1
)
上面生成数组的代码部分:
foreach ($this->request->post['quantity'] as $key => $value)
{
$cart_value[$key] = $value;
}
foreach ($this->session->data['cart'] as $id => $val) {
$stock[$id] = $this->cart->availableStock($id);
}
如何比较每个键的值?
我有这个 if else 语句:
if ($cart_value > $stock) {
// do something<br>
} elseif ($cart_value = $stock) {
// do another thing
} else {
// do this thing
}
感谢您的帮助。
用array_intersect_assoc on the arrays and then use count看结果是否一样大
或者,使用 array_diff_assoc 并查看结果是否为空。
一切都取决于你想对结果做什么。第一个选项将 return 包含匹配元素的数组,第二个选项将 return 包含不匹配元素的数组。
如果您希望结果基于特定公式(例如 return 只有第二个数组中值较大的项目),您可以使用 array_uintersect_assoc
您可以嵌套 foreach 循环。
foreach ($array1 as $k1 => $v1) {
foreach {$array2 as $k2 => $v2) {
if ($k1 === $k2) {
switch (true) {
case ($v1 < $v2):
// less than
break;
case ($v1 > $v2):
// more than
break;
case ($v1 == $v2):
// equal
break;
default:
// values cannot be compared
break;
}
}
}
}