php特定的数组中的单词

时间:2015-04-04 06:39:43

标签: php arrays foreach

我有2个数组,其中一个包含单词,其他单词和值。我有下面的代码将检查一个数组与另一个数组,并将添加值,并将返回总数。但是,如果字符串中有常用字,则代码也会为它们添加值。

如何才能获得下面示例中的确切单词Green的值? 就像下面的例子中一样,我应该是3而不是15。

$a_array = array( array("name"=> "Red", "price"=> "2"), 
array("name"=> "Green", "price"=> "3"), 
array("name"=> "Green Leaf", "price"=> "4"), 
array("name"=> "Green Light", "price"=> "8"), 
array("name"=> "Grey", "price"=> "1"), 
array("name"=> "Yellow", "price"=> "11"));


$check = array(Blue, Green, Black, );
$total = 0; foreach ($check as $key => $value): 
foreach ($a_array as $itemKey => $itemValue): 
if (strstr($itemValue['name'], $value)): 
$total += $itemValue['price']; 
continue; endif; endforeach; endforeach;


echo "Total: $total";

2 个答案:

答案 0 :(得分:0)

试试这个: -

<?php  
   $a_array = array( array("name"=> "Red", "price"=> "2"), 
   array("name"=> "Green", "price"=> "3"), 
   array("name"=> "Green Leaf", "price"=> "4"), 
   array("name"=> "Green Light", "price"=> "8"), 
   array("name"=> "Grey", "price"=> "1"), 
   array("name"=> "Yellow", "price"=> "11"));

   $check = array('Blue', 'Green', 'Black' );
   $total = 0; foreach ($check as $key => $value): 
   foreach ($a_array as $itemKey => $itemValue): 
   if ($itemValue['name']== $value): // condition is changed here
   $total += $itemValue['price']; 
   continue; endif; endforeach; endforeach;

   echo "Total: $total";
?>

输出为:总计:3

答案 1 :(得分:0)

使用下面的代码。而不是使用strstr函数来匹配字符串使用'=='运算符。

 if ($itemValue['name'] == $value): 

而不是

 if (strstr($itemValue['name'], $value)):