简体   繁体   English

在foreach循环中的最后两个数据库结果之间添加“和”

[英]Adding “and” between last two database results in foreach loop

I want to add the word "and" between the last two MySQL results. 我想在最后两个MySQL结果之间添加单词“and”。 I can add commas but I need to add commas between the first ones and then "and" between the last two. 我可以添加逗号,但我需要在第一个之间添加逗号,然后在最后两个之间添加“和”。

Here is the code I'm using: 这是我正在使用的代码:

        $not_first = false;

        foreach($solos as $solo)
        {
            if ($not_first)
            {
                echo ', ';
            }
            $not_first = true;

            echo $solo->id;
        }

I could echo 'and' instead of the comma. 我可以回应'和'而不是逗号。 But if I have 3 or more results it would say "result and result and result and result". 但如果我有3个或更多结果,它会说“结果和结果,结果和结果”。 I want it to say "result, result, result, and result". 我希望它说“结果,结果,结果和结果”。

Any ideas? 有任何想法吗?

Try to use next idea 尝试使用下一个想法

if (count($solos) > 2) {
    $last = array_pop($solos);
    echo implode(', ', $solos) . ' and ' . $last;
}
else
{
    echo implode(' and ', $solos);
}

I'd prefer using for instead of foreach in this case: 在这种情况下,我更喜欢使用for而不是foreach

for($i=0; $i<count($solos); $i++){
    echo $solos[$i]->id;

    if($i == count($solos) - 2){        // --> second last element, implies "and" 
        echo " and ";
    }
    else{
        if($i != count($solos) - 1){    // --> "," for all other elements, except last
            echo ", ";
        }    
    }
}

Or use this: 或者用这个:

   $i = 1;
   $last = count($solos);
    foreach($solos as $solo)
    {
        if ($i > 1 && $i != $last)
        {
            echo ', ';
        }
        elseif ( $i == $last )
        {
            echo ' and ';
        }

        echo $solo->id;
        $i++;
    }

you can count it and at second last id append "and" instead of "," 你可以数数它,在倒数第二个id附加“和”而不是“,”

$x = count($solos);
foreach($solos as $solo){
    echo $solo->id;
    if ($solos[$x - 2] == $solo){
        echo 'and';
    }elseif ($solos[$x -1] != $solo && $solos[0] != $solo){
        echo ',' 
    }
}

The other answers work perfectly. 其他答案完美无缺。 For the sake of completeness, you could also insert an "and" using preg_replace. 为了完整起见,您还可以使用preg_replace插入“和”。

$solos = array( 'one', 'two', 'three', 'four' );

$result = implode(', ',$solos);
$result = preg_replace('/, ([^,]+)$/',', and \1', $result);

Over 1 million iterations, mnv's array_pop method took 2.13 seconds. 超过100万次迭代, mnv的 array_pop方法耗时2.13秒。 preg_replace completed in 3.65 seconds. preg_replace在3.65秒内完成。 Using array_pop would be preferable. 使用array_pop会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM