How to edit the implode so it will join values with two strings?

て烟熏妆下的殇ゞ 提交于 2019-12-20 04:59:26

问题


In the function below a possible output maybe

1 day and 2 hours and 34 minutes

My question is how do I edit the implode so it will output

1 day, 2 houts and 34 minutes

This is my function

function time_difference($endtime){
    $hours = (int)date("G",$endtime);
    $mins = (int)date("i",$endtime);

    // join the values
    $diff = implode(' and ', $diff);

    if (($hours == 0 ) && ($mins == 0)) {
        $diff = "few seconds ago";
    }
    return $diff;
}

回答1:


I would do something like:

if ($days) {
    $diff .= "$days day";
    $diff .= $days > 1 ? "s" : "";
}
if ($hours) {
    $diff .= $diff ? ", " : "";
    $diff .= "$hours hour";
    $diff .= $hours > 1 ? "s" : "";
}
if ($mins) {
    $diff .= $diff ? " and " : "";
    $diff .= "$mins minute";
    $diff .= $mins > 1 ? "s" : "";
}



回答2:


Something like this?

function implodeEx($glue, $pieces, $glueEx = null)
{
    if ($glueEx === null)
        return implode($glue, $pieces);
    $c = count($pieces);
    if ($c <= 2)
        return implode($glueEx, $pieces);

    $lastPiece = array_pop($pieces);
    return implode($glue, array_splice($pieces, 0, $c - 1)) . $glueEx . $lastPiece;
}

$a = array('a', 'b', 'c', 'd', 'e');
echo implodeEx(',', $a, ' and ');



回答3:


There are a lot of places for x-time-ago functions. here are two in PHP. Here's one in Javascript.



来源:https://stackoverflow.com/questions/7613847/how-to-edit-the-implode-so-it-will-join-values-with-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!