duancong2965 2016-06-06 22:30
浏览 115
已采纳

php替换数组值

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!

展开全部

  • 写回答

2条回答 默认 最新

  • dongmaijie5200 2016-06-06 22:48
    关注

    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']);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部