简体   繁体   中英

PHP - Find max/highest value

I have this query:

    $stmt=$dbh->prepare("select round((expire - unix_timestamp()) / 86400) as days, count(*) as cnt from xeon_users_rented WHERE user_by=:username group by days;");
    $stmt->bindParam(":username",$userdata['username']);
    $stmt->execute();
    $data=$stmt->fetchAll();

Which returns this array result var_dump($data) :

array(2) {
  [0]=>
  array(4) {
    ["days"]=>
    string(2) "27"
    [0]=>
    string(2) "27"
    ["cnt"]=>
    string(1) "2"
    [1]=>
    string(1) "2"
  }
  [1]=>
  array(4) {
    ["days"]=>
    string(3) "116"
    [0]=>
    string(3) "116"
    ["cnt"]=>
    string(1) "8"
    [1]=>
    string(1) "8"
  }
}

I then want to get the highest value of the $data result:

echo max($data["days"]);    

Althoug that doesn't work, as nothing is getting echoed out. What am I doing wrong?

wouldn't

SELECT MAX(column_name) FROM table_name;

Do that in query already? Selecting only the highest value - therefor saving bandwidth and wont require loops to waste even more resources. All tho i cannot test it with your specific query.

$data['days'] isn't an array. You have an array of arrays, each of which has its own 'days' element.

You could map your 'days' elements to an array and then get the max() :

echo max(array_map(function($d){
    return $d['days'];
}, $data));

Demo

As i see your array is 2 dimensional, you need to loop through both of this array and then get max from them.

for($i=0;$i<=sizeof($data);$i++) { echo max($data[$i]["days"]); }

This should solve your problems.

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