2013-03-25 38 views
-2

返回我有這樣一個查詢:找到陣列的while循環最小值從MySQL查詢

select * from posts p where p.post like '%cadillac%' ORDER BY p.upvotes DESC, 
p.unix_timestamp DESC LIMIT 20 

現在,同時通過陣列循環,我需要找到最小unix_timestamp值。例如:

$counter = 0; 
while($row = $result->fetch_assoc()){ 

// what do i do here to find the minimum timestamp value 

$counter = $counter + 1; 
} 

請指教。

+1

這聽起來很簡單,也許我沒有得到題吧...店檢查變量中的unix_timestamp值,並檢查當前行的值是否較小,如果是,則將該值保存在變量中。 – Eggplant 2013-03-25 17:37:14

+0

爲什麼如果我可能會問這個投票呢? – coder101 2013-03-25 17:47:12

回答

2
$counter = 0; 
$min_timestamp = 0; 
while($row = $result->fetch_assoc()){ 

    //check if min hasn't been set OR if the current timestamp is less than the min 
    if(!$min_timestamp || ($row['unix_timestamp'] < $min_timestamp)) { 
     //store this timestamp as the current min 
     $min_timestamp = $row['unix_timestamp']; 
    } 

    //$counter = $counter + 1; 
} 
//once we reach here, min_timestamp will hold the minimum timestamp found 
+1

當您測試所有值爲0時,這將如何返回最小值? – coder101 2013-03-25 17:52:19

+0

刪除'$ min_timestamp = 0;'並添加'if(!isset($ min_timestamp))$ min_timestamp = $ row ['unix_timestamp'];'在循環內或預取第一行 – Waygood 2013-03-25 17:56:06

+0

@ coder101我不確定我理解你的問題:它將在第一次傳遞時進入if(),並將第一行unix_ts分配給$ min_timestamp變量。 – Alexey 2013-03-25 18:00:09

0

您可以在SQL

select MIN(unix_timestamp) from posts p where p.post like '%cadillac%' 
+0

這不是他要求的,因爲它會影響回來的行數。 – 2013-03-25 17:38:37

+0

我也想要所有其他的字段值。所以可能就像'select MIN(unix_timestamp),p。* from post p where p.post like'%cadillac%'ORDER BY p.upvotes DESC, p.unix_timestamp DESC LIMIT 20'。它是否正確? – coder101 2013-03-25 17:39:01

+0

@JimmySawczuk認爲這是他問的問題。 – 75inchpianist 2013-03-25 17:39:24

1

做到這一點,下面的工作:

$counter = 0; 
$min_value; 
while($row = $result->fetch_assoc()){ 
    $min_value = is_null($min_value) || $min_value > $row['unix_timestamp'] ? $row['unix_timestamp'] :$min_value ; 

    $counter = $counter + 1; 
} 
+0

這不行。 $ min_value在這裏始終爲空,因爲您每次都要設置$ min_value = $ min_value。 ||將永遠評估爲真。 – 75inchpianist 2013-03-25 18:07:53

+0

翻轉你的價值觀的權利?它會工作 – 75inchpianist 2013-03-25 18:08:54

+0

@ 75inchpianist你是對的,也換了< for a > – 2013-03-25 18:10:52