Steve Kim
Steve Kim

Reputation: 5591

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!

Upvotes: 1

Views: 311

Answers (3)

mickmackusa
mickmackusa

Reputation: 47934

Because you are processing an array of objects -- and objects are modifiable by reference by default -- you can set up ago() to modify by reference as well and use array_walk().

Code: (Demo)

function ago(&$v) {
    $v = date('M Y', strtotime($v)); // do whatever
}

array_walk($array, fn($obj) => ago($obj->date));
var_export($array);

Output:

array (
  0 => 
  (object) array(
     'ID' => 4983,
     'post_id' => 56357,
     'date' => 'Jun 2016',
  ),
  1 => 
  (object) array(
     'ID' => 4982,
     'post_id' => 56241,
     'date' => 'Jun 2016',
  ),
)

Using PHP7.4's arrow function syntax means you dont need to use use() to bring ago() into array_walk()'s callback scope. Also, array_walk() will ignore the return value generated by the arrow.

Upvotes: 0

Chetan Ameta
Chetan Ameta

Reputation: 7896

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']);
});

Upvotes: 1

Guillaume Renoult
Guillaume Renoult

Reputation: 966

You would need to loop through your result and call the ago function:

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

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

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

I haven't tested it but you have the idea.

Upvotes: 2

Related Questions