2013-04-02 104 views
0

我正在製作一個圖像網站,我需要時間戳排序幫助。我有大約5個不同的SQL查詢來從數據庫中獲取信息。每個查詢都會得到時間戳。PHP:時間戳排序

我想要做的是從數據庫中獲取它,並使用foreach循環對所有查詢中的圖像進行排序。這可能聽起來很混亂,只是如果你不明白就發表評論。

$images = array(); 

$stmt = $conn->prepare("SELECT images.*, group_images.* ORDER BY `timestamp` DESC"); 
$stmt->execute(); 

while ($images_row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    $images[] = array(
    'image_id' => $images_row['image_id']); 
} 
return $images; 

foreach($images as $image) { 
    echo $image['image_id']; 
    echo '<br/>'; 
} 

這是我試圖嘗試的查詢結果不起作用。

錯誤:

$images = valley_images();

$sorted_data = array(); 

foreach($images as $key => $value) { 
    if ($key == 'timestamp') { 
     $sorted_data[$value][] = $images; 
    } 
} 

ksort($sorted_data); 
+0

我們可以看到您的數據庫結構和您嘗試過的任何PHP嗎? – showdev

回答

1

If I understand you correctly, this might help:

$data; //data from database, assuming it has a "timestamp"-key 
$sorted_data = array(); 

foreach ($data as $key => $value) { 
    if ($key == 'timestamp') { 
     $sorted_data[$value][] = $data; 
    } 
} 

ksort($sorted_data); 

With that you get an array that is ordered by the timestamps of your values from the database. If there is only one entry to each timestamp you can spare the []

+0

這看起來不錯,唯一的問題是,我將如何將所有查詢分配給$數據? – Tuccinator

+0

例如,使用$ data = $ query1 + $ query2 + $ query3 ...有很多不同的方法可以合併你的數組(參見http://php.net/manual/de/function.array-merge.php)。這取決於從數據庫獲取數據時數據的外觀。 – hurrtz

+0

我看到了,非常感謝!現在我必須在$ sorted_data中回顯每個圖像。我將如何去做這件事?我通常使用我發佈在主帖子中的foreach循環。 – Tuccinator