php - 将字符串与数组进行比较并添加结果

php - comparing a string to an array adding the results

我有一个字符串和一个数组。我想将字符串中的单词与包含相同单词及其值的数组进行比较,并为所有常用单词添加值。即:

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

下面的代码应该有很好的文档记录。让我知道这是否是您想要的:

$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;

@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;