Jump to content

[SOLVED] How to quickly determine the max element in a column/array ?


tmyonline

Recommended Posts

Hi guys:

 

Here I have:

 

$SQL      = "SELECT element_key, matrix_num FROM matrix";

$Result  = mysql_db_query($db,$SQL,$cid);

 

I would like to find the maximum element in the element_key column and that in the matrix_num column.  This is what I did but it didn't work.

 

$element          = $Result['element_key'];

$max_element    = max($element);

 

$matrixNum        = $Result['matrix_num'];

$max_matrixNum = max($matrixNum);

 

What's wrong with my syntax and what's the best way to do this?  Thanks a lot.

 

T

Hi Ben,

 

I understand your SQL.  It is very efficient but then what ?!  So I have:

 

$sql    = "SELECT MAX(element_key) AS max_element_key, MAX(matrix_num) AS max_matrix_num FROM matrix";

$result = mysql_db_query($db,$sql,$cid);

 

I tried to do:

$max_element    = $result['max_element_key'];

$max_matrixNum = $result['max_matrix_num'];

 

echo $max_element . '<br />';

echo $max_matrixNum

 

but I didn't see anything !

Well, you're using a user defined function, mysql_db_query - i dont know what it returns - does it return an array?. If you're not sure either, then try:

 

$sql     = "SELECT MAX(element_key) AS max_element_key, MAX(matrix_num) AS max_matrix_num FROM matrix";
$result = mysql_db_query($db,$sql,$cid);
var_dump($result);

 

And see what you get

Hi Ben,

 

I did as you suggested.

 

$sql            = "SELECT MAX(element_key) AS max_element_key, MAX(matrix_num) AS max_matrix_num FROM matrix";

$matrixResult = mysql_db_query($db,$sql,$cid);

$result        = var_dump($matrixResult);

 

echo $result;

echo $result['max_element_key'];

 

Here's the output:

 

resource(5) of type (mysql result) which I have no idea what it is!

Ok, its returning the same thing that a normal mysql_query would do - a result resource. Try:

 

 

$sql = "SELECT MAX(element_key) AS max_element_key, MAX(matrix_num) AS max_matrix_num FROM matrix";
$matrixResult = mysql_db_query($db,$sql,$cid);
$result = mysql_fetch_assoc($maxtrixResult);
echo $result['max_element_key'];

 

 

 

You need to fetch the results after doing the query:

<?php
$sql             = "SELECT MAX(element_key) AS max_element_key, MAX(matrix_num) AS max_matrix_num FROM matrix";
$rs = mysql_query($sql);
$rw = mysql_fetch_assoc($rs);
echo $rw['max_element_key'] . ' ... ' . $rw['max_matrix_num'] . '<br>';
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.