Neea February 2016

Sorting out rows with same timestamp

I have mysql table that only has key, value and timestamp in it. The data comes from a form and every from field adds an key value pair and all of them have the same timestamp. Now they come out like that :

 [0] => Array
        (
            [key] => name
            [value] => john
            [timestamp] => 2016-02-08 14:16:00
        )

    [1] => Array
        (
            [key] => email
            [value] => john$john.com
            [timestamp] => 2016-02-08 14:16:00
        )

    [2] => Array
        (
            [key] => name
            [value] => guru
            [timestamp] => 2016-02-08 14:16:05
        )

    [3] => Array
        (
            [key] => email
            [value] => test@gmail.com
            [timestamp] => 2016-02-08 14:16:05
        )

What I would like it to do is to take the key-value pairs with same timestamp and print them out in a one row and then the next timestamp in next row. Im using php.

Thanks for the help :)

Answers


Egg February 2016

You'll want to store the timestamp to check against on the next pass.

$previous = null;
foreach ($array AS $item) {
    if ($previous == $item['timestamp']) {
        // Do this on the same row as we already have one like this.
    } else {
        // Do this on a new row as it's the first of its kind.
    }

    // Save the timestmap to use on the next pass of the loop.
    $previous = $item['timestamp'];
}

Hopefully this gives you somewhere to start from.


Diego Mariani February 2016

Your question is not quite clear, but I think that's what you'd like to obtain. Just use a foreach

$last = 0;
foreach($data as $row) {
    if ($last != $row['timestamp'])
        echo "\r\n";

    $last = $row['timestamp'];
    echo $row['key'] . ':' . $row['value'] . ' ';
}

Post Status

Asked in February 2016
Viewed 2,019 times
Voted 10
Answered 2 times

Search




Leave an answer