替换字符串中的一些值

时间:2014-07-03 15:48:02

标签: php string

所以我试图让下面的代码只替换字符串中的值,因此Maths = 1,English = 1,Media(短程)= 0.5。所以这应该输出2.5,但是它输出14.我猜这意味着它将数组中的所有值相加。

所以我想用一些数值替换字符串中的值然后将它们相加。有什么想法吗?

$strg2 = 'Maths, English, Media (Short course)';

$gcse = explode(',', $strg2);
$gcse = array(
'Maths' => '1',
'English' => '1',
'EnglishLit' => '1',
'Science' => '1',
'Art' => '1',
'ICT (full course)' => '1',
'ICT (Short course)' => '0.5',
'Media (Full course)' => '1',
'Media (Short course)' => '0.5',
'Geography' => '1',
'History' => '1',
'ChildCare' => '1',
'Religious' => '1',
'Electronics' => '1',
'Higher' => '0.5',
'Foundation' => '0.5');

echo array_sum($gcse);

2 个答案:

答案 0 :(得分:1)

我认为你正试图创造一个"得分"基于输入字符串$strg2。您需要将该字符串拆分为一个数组,然后迭代它,将课程与$gcse数组的值相匹配。

$strg2 = 'Maths, English, Media (Short course)';

$gcse = array(
'Maths' => '1',
'English' => '1',
'EnglishLit' => '1',
'Science' => '1',
'Art' => '1',
'ICT (full course)' => '1',
'ICT (Short course)' => '0.5',
'Media (Full course)' => '1',
'Media (Short course)' => '0.5',
'Geography' => '1',
'History' => '1',
'ChildCare' => '1',
'Religious' => '1',
'Electronics' => '1',
'Higher' => '0.5',
'Foundation' => '0.5');

$lessons = explode(',', $strg2); // Split the string into an array that can be iterated
$n = 0;

foreach ($lessons as $lesson) {

    $n += $gcse[trim($lesson)]; // n = n + the value of lesson

}

echo $n;

答案 1 :(得分:0)

如果只想使用数组操作,可以执行以下操作:

$lessons = explode(',', $strg2);
$lessons = array_map('trim', $lessons);
$lessons = array_flip($lessons);
$result = array_intersect_key($gcse, $lessons);

echo array_sum($result);

否则,@ beingalex提出的解决方案在所有情况下都会更快。

<强> PS: 只是为了好玩,一个班轮:

echo array_sum(array_intersect_key($gcse, array_flip(array_map('trim', explode(',', $strg2)))));