|
-
May 22nd, 2005, 12:00 PM
#1
Thread Starter
Fanatic Member
Average of values in a string? [Resolved]
Hello all,
I came across a problem with calc an average, the thing is, i have a big string, full of values separated using ; and ,
Let me show:
$myString="1,2;2,2;1,3;2,3;2,4";
The average of that should return something like:
(1+2+1+2+2)/5
and
(2+2+3+3+4)/5
That string has 2 answers for 1 question, that would do 2 averages, not just one in this case.
Answer 1 would be 1,6
Answer 2 would be 2,8
The answers schema is: <answer1>,<answer2>;<answer1>,<answer2>;...
But it can be <answer1>,<answer2><answer3>;<answer1>,<answer2><answer3>;...
or
<answer1>;<answer1>;<answer1>;...
Does anyone have any idea on how to solve this?
Last edited by TDQWERTY; May 28th, 2005 at 02:02 AM.
-
May 24th, 2005, 01:42 AM
#2
Re: Average of values in a string?
Here is what you need to do:
- Use the split() function to turn the string into an array using a semi colon as a separator.
- For each string in this new array:
- Use the split() function again, but this time use the comma as a separator and you obtain an array of number.
- For each number in this array append it to a new array containing the answers for each question:
PHP Code:
$count = count($answer_array);
for($x = 0; $x < $count; $x++) {
$question_array[$x + 1][] = $answer_array;
}
- Your question array should contain an index for each question number, each element being an array of answers. You can then loop through this array and calculate the average for each with the help of the array_sum() function.
PHP Code:
foreach($question_array as $question_number => $answers) {
$average_array[$question_number] = array_sum($answers) / count($answers);
}
- You will now have an array of averages for each question.
-
May 24th, 2005, 10:10 AM
#3
Thread Starter
Fanatic Member
Re: Average of values in a string?
thanks a lot!
5 Points for your answer, my question has been answered at first!
It works like a charm!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|