我有一个字符串和一个数组。我想比较字符串中的单词与包含相同单词及其值的数组,并为所有常用单词添加值。即:
This is the string:
$check = "red plate fork red plate";
This array is my array:
$arrayItems = array(
array("name" => "red plate", "price" => 12.00),
array("name" => "plate", "price" => 8.00),
array("name" => "blue spoon", "price" => 6.50),
array("name" => "fork", "price" => 5.75));
如何获得$ total,在这种情况下是:12 + 5.75 + 12 = 29.75
答案 0 :(得分:0)
以下代码应该有详细记录。如果这是您想要的,请告诉我:
$check = "plate fork plate";
$arrayItems = array(
array("name" => "plate", "price" => 12.00),
array("name" => "spoon", "price" => 6.50),
array("name" => "fork", "price" => 5.75));
$totalPrice = 0;
/*we don't need the extra spaces, just the exact term*/
$checkIsolated = explode(" ", $check);
foreach ($checkIsolated as $key => $value):
/*loop through the actual item price list to match whatever */
/*checkIsolated array holds*/
foreach ($arrayItems as $itemKey => $itemValue):
/*a match is found! let's get the corresponding price! :)*/
if (strstr($itemValue['name'], $value)):
$totalPrice += $itemValue['price'];
continue; /*let's save extra cpu usage here.*/
endif;
endforeach;
endforeach;
echo 'Total Price is: ' . $totalPrice;
答案 1 :(得分:0)
@Steve你可以这样做。
$str = "plate,fork,red plate";
$strArr = explode(",", $str);
$arr = array(array( "name" => 'red plate', "price" => '50'),array( "name" => 'plate', "price" => '50'),array( "name" => 'fork', "price" => '25'));
$total = 0;
foreach ($strArr as $key => $value){
foreach ($arr as $arrkey => $arrvalue){
if (strstr($arrvalue['name'], $value)){
$total = $total + $arrvalue['price'];
}
}
}
echo $total;