Skip to content
Advertisement

php replace array value

I have following mysql query function:

$query_number = 2;
$query        = "SELECT * FROM $table ORDER by date desc limit $query_number";  
$results      = mysql_query($query);    

$message['posts']    = $results;
echo json_encode($message); 
exit;

I get an array of objects with multiple keys:

Array
(
[0] => stdClass Object
    (
        [ID] => 4983
        [post_id] => 56357
        [date] => 2016-06-04 23:45:28          
    )

[1] => stdClass Object
    (
        [ID] => 4982
        [post_id] => 56241
        [date] => 2016-06-04 22:58:27           
    )
 )

I am sending the whole array to the js via ajax.

However, I want to change the date format to “ago” and send it to js.

I have the “ago” function, but I am not sure how to target the date value and put it back to its original place (replacement).

Any help would be much appreciate!

Thanks!

Advertisement

Answer

To replace value you can use foreach and change variable on same address

foreach($results as &$row) {
    // Replace date value with ago value
    $row['date'] = ago($row['date']);
}

$message['posts']    = $results;
echo json_encode($message);

If you dont want to use foreach then you can use array_walk function in place of foreach:

array_walk($results, function(&$row){
    $row['date'] = ago($row['date']);
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement