Joe
Joe

Reputation: 63

Modify every value of specified key in array

I've got a database with multiple rows and columns, which are grabbed with PDO.

$sql     = "SELECT timestamp FROM table";
$stmt    = $dbh->prepare($sql);
$results = $stmt->execute;
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

One of the database columns is timestamp which is a 10 digit unix timestamp. I'd like to convert this server side to a readable format before sending it to the browser.

This is how I'd like it to be formatted, but I know it needs to be done on every row and this is where it trips me up. Possibly a foreach loop?

$results['timestamp'] = date('H:i\, l jS \of F Y', $results['timestamp']);

Upvotes: 0

Views: 62

Answers (2)

Joe
Joe

Reputation: 63

Figured it out :)

array_walk($results, function(&$value) {
    $value['timestamp'] = date('H:i\, l jS \of F Y', $value['timestamp']);
}

Upvotes: 0

Marc B
Marc B

Reputation: 360772

Much simpler to do that in the DB directly, since the DB will already be "looping" on the exact same data, saving you having to reloop in client-side code:

SELECT DATE_FORMAT(timestamp, '%H:%i, etc...') FROM table

The format codes are documented here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Upvotes: 3

Related Questions