简体   繁体   中英

Trouble with extracting a value from an associative array

I am having some basics trouble with PHP. I want to retrieve an average of a column of numbers from a MYSQL database. I am using SELECT AVG() to get the result in the database. The issue is that what is returned is not a floating number but an associative array with one key:value. This is the kind of thing I am getting back in json form:

array(1) { [0]=> array(1) { ["AVG(enterpriseAppDev.employee.age)"]=> string(7) "54.4538" } }

In my PHP project I am assigning the above to a variable $average.

Can anyone tell me how I can extract the value (54.4538) the the $average variable and use it later on?

I have tried to use a foreach loop to get the value like this

foreach ($average as $x => $x_value) {
    $average = $x_value;
    return $average;
}

I have also tried to do the standard Deviation in SQL using STDEV and STDEVP but I get an error saying these functions do not exist.

Any help would be much appreciated.

2 problems :
you assign the value $average into the loop whereas it is in the loop parameter... can cause a crash...
so you could use return $x_value without getting it into $average .
then, you don't need a loop here just do this (with NO loop)
return $average[0]['AVG(enterpriseAppDev.employee.age)']

if you really want a loop you can do this :

foreach ($average as $line_number => $line) {
    foreach($line as $key => $x_value) {
        return $x_value;
    }
}

1. If you'll always get this multidimensional array you can reset the internal pointer of the array with reset to "flatten" the first one. And this should do the trick:

var_dump(reset($average[0]));

// or you can do it twice to get the same result as before
$average = reset($average);
var_dump(reset($average)); 

2. But probably you can get a better key name using an alias in your SQL:

SELECT AVG() AS myavg

// so you should end up with a result like:

$queryResult = array(
    array(
        "myavg" => "54.4538"
    )
);

// and get the average
$average = reset($queryResult);
var_dump($average['myavg']);

3. Or even more weird, if you're using php 5.4 where you can get an array reference directly from a function result:

var_dump(reset($average)['avg']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM