PHP 形成字符串“A、B、C 和 D”从数组值

发布于 2024-11-15 08:24:16 字数 649 浏览 2 评论 0原文

给定以下数组:

Array
(
    [143] => Car #1
    [144] => Car #2
    [145] => Car #3
)

我目前正在使用它

implode(', ', array_values($car_names))

来生成类似的字符串

1 号车、2 号车、3 号车

我实际上想要得到类似的东西

1 号车、2 号车和 3 号车

这个想法是在数组的最后两个元素之间插入 " 和 "

如果数组恰好包含两个键/值对(例如,用户有 2 辆车),则不会有逗号。

1 号车和 2 号车

如果数组包含一个键/值(例如,用户有 1 辆车)

1 号车

有什么建议如何完成这个任务吗?我尝试使用 array_splice ,但我不确定这是否可行(即向数组中插入新元素)。

感谢您的帮助!

Given the following array:

Array
(
    [143] => Car #1
    [144] => Car #2
    [145] => Car #3
)

I am currently using this

implode(', ', array_values($car_names))

to generate a string like

Car #1, Car #2, Car #3

I would like to actually get something like

Car #1, Car #2 and Car #3

The idea would be to insert " and " between the two last elements of the array.

If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.

Car #1 and Car #2

And if the array contains one key/value (eg, user has 1 car)

Car #1

Any suggestion how to get this done? I tried using array_splice but I'm not sure that's the way to go (ie, inserting a new element into the array).

Thanks for helping!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

风吹过旳痕迹 2024-11-22 08:24:16
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
夏至、离别 2024-11-22 08:24:16

我想你可能想要这样的东西,使用 array_pop< /a> 获取数组末尾的最后一个元素。然后,您可以内爆数组的其余部分,并以自定义方式添加最后一个元素:

$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;

编辑:添加条件以检查数组是否只有一个元素。

I think you probably want something like this, using array_pop to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:

$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;

Edit: added conditional to check if the array had only one element.

过去的过去 2024-11-22 08:24:16

preg_replace 可以查找最后一个命令,只需将其交换为 and

$yourString = preg_replace( "/, ([\w#]*)$/", "and \1", $yourString );

A preg_replace can look for the last command just just swap it to an and

$yourString = preg_replace( "/, ([\w#]*)$/", "and \1", $yourString );
旧瑾黎汐 2024-11-22 08:24:16

这个解决方案有点长,但经过了所有数组大小的测试,它是一个完整的解决方案。此外,它不会像上面的答案那样修改数组,而是被分成一个函数。

function arrayToString($arr) {
    $count = count($arr);
    if ($count <= 2) {
        return implode(' and ', $arr);
    }
    $result = '';
    $i = 0;
    foreach ($arr as $item) {
        if ($i) $result .= ($i == $count - 1) ? ' and ' : ', ';
        $result .= $item;
        $i++;
    }
    return $result;
}

压缩版本具有丑陋的格式并忽略初始化变量等良好实践:

function arrayToString($arr) {
    if (count($arr) <= 2) return implode(' and ', $arr);
    foreach ($arr as $item) {
        if ($i) $result .= ($i == count($arr) - 1) ? ' and ' : ', ';
        $result .= $item; $i++;
    }
    return $result;
}

This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn't modify the array like the above answers and is separated into a function.

function arrayToString($arr) {
    $count = count($arr);
    if ($count <= 2) {
        return implode(' and ', $arr);
    }
    $result = '';
    $i = 0;
    foreach ($arr as $item) {
        if ($i) $result .= ($i == $count - 1) ? ' and ' : ', ';
        $result .= $item;
        $i++;
    }
    return $result;
}

Compacted version with ugly formatting and ignoring good practices like initializing variables:

function arrayToString($arr) {
    if (count($arr) <= 2) return implode(' and ', $arr);
    foreach ($arr as $item) {
        if ($i) $result .= ($i == count($arr) - 1) ? ' and ' : ', ';
        $result .= $item; $i++;
    }
    return $result;
}
洛阳烟雨空心柳 2024-11-22 08:24:16

我不确定是否有内置函数,但类似的东西应该可以工作。

$last = $car_names[count($car_names)-1];
$implodedString = implode(', ', array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);

I'm not sure there's a built in function for this, but something like this should work.

$last = $car_names[count($car_names)-1];
$implodedString = implode(', ', array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);
破晓 2024-11-22 08:24:16

这是我上面的评论中命名的函数的示例:

  1. strrpos() - 查找字符串中子字符串最后一次出现的位置
  2. substr() - 返回字符串的一部分

和代码:

$text = implode(', ', array_values($car_names));
$last = strrpos($text, ',');
if ($last) $text = substr($text, 0, $last-1) . ' AND ' . substr($text, $last+1);
echo $text;

That's an example with the functions named in my comment above:

  1. strrpos() - Find the position of the last occurrence of a substring in a string
  2. substr() - Return part of a string

and the code:

$text = implode(', ', array_values($car_names));
$last = strrpos($text, ',');
if ($last) $text = substr($text, 0, $last-1) . ' AND ' . substr($text, $last+1);
echo $text;
被你宠の有点坏 2024-11-22 08:24:16

有多种方法可以做到这一点。这是另一个。

<?php
$cars = array('Car #1', 'Car #2', 'Car #3', 'Car #4');
$car = array('Car #1');
$twocars = array('Car #1', 'Car #2');

function arrayToText($arr) {
    switch (count($arr)) {
    case 1:
        return $arr[0];
        break;
    case 2:
        return implode($arr, ' and ');
        break;
    default:
        $last = array_pop($arr);
        return implode($arr, ', ') . ' and ' . $last;
        break;
    }
}

echo '<p>' . arrayToText($cars) . "</p>\n";
echo '<p>' . arrayToText($twocars) . "</p>\n";
echo '<p>' . arrayToText($car) . "</p>\n";

输出

<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>

There are a number of ways you could do this. Here's another.

<?php
$cars = array('Car #1', 'Car #2', 'Car #3', 'Car #4');
$car = array('Car #1');
$twocars = array('Car #1', 'Car #2');

function arrayToText($arr) {
    switch (count($arr)) {
    case 1:
        return $arr[0];
        break;
    case 2:
        return implode($arr, ' and ');
        break;
    default:
        $last = array_pop($arr);
        return implode($arr, ', ') . ' and ' . $last;
        break;
    }
}

echo '<p>' . arrayToText($cars) . "</p>\n";
echo '<p>' . arrayToText($twocars) . "</p>\n";
echo '<p>' . arrayToText($car) . "</p>\n";

Output

<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文