Ben21
Ben21

Reputation: 35

Adding data from an array to a new array

I have created an array of data, from which I can loop through specific fields and echo these values out, but what I need to do is add these values to a new array, ultimately allowing me to find the average of the values in the new array. As i've said, I can echo out the data, and I think I've figured how to get the average, if only I can create the new array! Any help would be greatly appreciated as I just can't find the answer anywhere, and I'm running low on talent!

My table contains approx 25 fields, im pulling out a number of rows based on a session variable. In the instance im working on, I need to take just the values from 1 column in the table, and add these to an array. The code below will loop through the values, and echo them out, 1 at a time:-

while ($cdarray=mysql_fetch_array($calldata))   {
echo $cdarray['score_total'];
}

This gives me 25555 which are the 4 values I would expect 25, 5, 5, 5

I've tried

while ($cdarray=mysql_fetch_array($calldata))   {
$cdts = $cdarray['score_total'];
$cdtsar = array($cdts);
}

Which results in $cdts being assigned a value of 5,

Any help greatly appreciated!!

Upvotes: 1

Views: 69

Answers (3)

nithi
nithi

Reputation: 3877

If you want to assign the elements to the new array use like this

$cdtsar = array();
while ($cdarray=mysql_fetch_array($calldata))   {
    array_push($cdtsar,$cdarray['score_total']);
}

To find the average of the array

$sum = array_sum($cdtsar);
$num = sizeof($cdtsar);
$avg = $sum/$num;
echo $avg;

Upvotes: 0

Jon
Jon

Reputation: 437336

It actually prints 25 and 5 and 5 and 5, but there are no spaces in between so it looks like "25555". To verify this yourself:

while ($cdarray=mysql_fetch_array($calldata))   {
    echo $cdarray['score_total'];
    echo " / ";
}

To get the average, you can either use

$sum = $count = 0;
$average = null;
while ($cdarray=mysql_fetch_array($calldata))   {
    $sum += $cdarray['score_total'];
    ++$count;
}

// Make sure to guard against divide by zero
if ($count) {
    $average = $sum / $count;
}

or you might have the database calculate the average for you, if changing the query is an option.

Upvotes: 1

LHolleman
LHolleman

Reputation: 2596

This will get your data from the array, place it into a new one and calculates the average.

$cdtsar = array();

while ($cdarray=mysql_fetch_array($calldata))   {
 $cdtsar[] = $cdarray['score_total'];
}

$average = array_sum($cdtsar) / count($cdtsar);

Upvotes: 1

Related Questions