[英]How to compare two values in one associate array in PHP
I am trying to compare two prices within an associative array. 我正在尝试在关联数组中比较两个价格。 I need to pull both prices out so that I can make a calculation.
我需要将两个价格都拉出来,以便进行计算。 The array I have is:
我拥有的数组是:
[10] => Array
(
[A Is For Annabelle 681 2 (fat Quarter)] => 2.8500
[A Is For Annabelle 681 2 (yardage)] => 7.9500
)
And the code i'm trying is: 我正在尝试的代码是:
$fqPrice;
$ydPrice;
foreach ($value as $key => $value) {
if (strpos($key, 'yd') !== false || strpos($key, 'yardage') !== false ) {
$ydPrice = $value;
}
if (strpos($key, 'fq') !== false || strpos($key, 'fat quarter') !== false ) {
$fqPrice = $value;
}
}
It gets to the first if statement but doesn't execute the second one. 它到达第一个if语句,但不执行第二个if语句。
well, your second one IS being executed, but it returns false
on both expressions; 好吧,您的第二个IS正在执行,但是在两个表达式上都返回
false
; so it means the $value
will not be assigned to $fqPrice
. 因此,这意味着
$value
不会分配给$fqPrice
。
You need to remember that strpos()
is case-sensitive , you can either change to use strpos($key, 'fat Quarter')
or use the stripos
function instead. 您需要记住
strpos()
区分大小写 ,您可以更改为使用strpos($key, 'fat Quarter')
或使用stripos
函数。
adding the extra array dimension loop (you probably already have this), i changed to a preg_match
which is 'cleaner': 添加额外的数组维度循环(您可能已经拥有了),我更改为
preg_match
,它更“干净”:
<?php
$value = array(10=>array('A Is For Annabelle 681 2 (fat Quarter)'=>'2.8500','A Is For Annabelle 681 2 (yardage)'=>'7.9500'));
$ydPrice=$fqPrice='';
foreach ($value as $first){
foreach ($first as $key=>$value){
if (preg_match('#yd|yardage#',$key)){
$ydPrice = $value;
}
if (preg_match('#fq|fat Quarter#',$key)){
$fqPrice = $value;
}
}
}
echo 'y=' . $ydPrice;
echo 'f=' . $fqPrice;
?>
demo: http://ideone.com/JTJNWx 演示: http : //ideone.com/JTJNWx
if your only interest in $value[10]
, you can just use foreach($value[10] as $key=>$value){}
如果您只对
$value[10]
感兴趣,则可以只使用foreach($value[10] as $key=>$value){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.