сравнивая строку с массивом, добавляя результаты

У меня есть строка и массив. Я хочу сравнить слова в строке с массивом, который содержит те же слова и их значение, и добавить значение для всех распространенных слов. то есть:

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

Как я могу получить сумму $, которая в этом случае: 12 + 5.75 + 12 = 29.75

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

Другие решения

@ Стив, ты можешь сделать это.

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