How to edit the implode so it will join values wit

2019-03-03 02:06发布

问题:

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.