0

I am making an image website and I need help with timestamp sorting. I have about 5 different SQL queries to get information from the database. Each one of these queries get the timestamp.

What I want to do is get it from the database, and sort the images from all of the queries with a foreach loop. This may sound confusing, just comment if you don't understand.

$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/>';
}

That is a query I attempted to try which turned out not to work.

Error:

$images = valley_images();

$sorted_data = array();

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

ksort($sorted_data);
1
  • Can we see your database structure and any PHP you've tried? Commented Apr 2, 2013 at 22:51

1 Answer 1

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 [].

Sign up to request clarification or add additional context in comments.

6 Comments

That looks pretty good, only thing is, how would I assign all my queries to $data?
For example with $data = $query1 + $query2 + $query3... There are many different ways to merge your arrays (see php.net/manual/de/function.array-merge.php). It depends on how your data looks like when you get it from your database.
Ah I see, thank you very much! Now I have to echo out each image within $sorted_data. How would I go about this? I usually use the foreach loop that I posted in the main post.
Can't tell you your way from here, because I don't know the structure and content of your new array ;) But if your loop worked before - why wouldn't it now? I'd just try it. If it doesn't work and you can't figure it out, try posting a new question. I guess that the current question got answered to your satisfaction :)
I am receiving "Illegal Offset type on line $sorted_data[$value][] = $images;" I added code to main post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.