如何从另一个逗号分隔列表中获取从 y 开始的 x 项的逗号分隔列表

How to get a comma separated list of x items starting from y from another comma seperated list

假设我有一个列表 Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco。 我想要一个从第 3 个项目开始的列表,总共有 5 个项目。这意味着我想要 England,China,Uruguay,Spain,Taiwan.

如何在 PHP 上执行此操作?

您可以像

一样简单地将字符串转换为数组
$str = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$array = explode(",",$str);

然后使用 array_slice 跳过前 2 项

print_r(implode(",",array_slice($array,2)));

<?php
$list = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$listArray = explode(",",$list);
print_r($listArray);
$startlist = 3; // Here you can set where you have start
if($startlist<count($listArray)){
    print_r(implode(",",array_slice($listArray,$startlist)));
}else{
    echo "Start limit exceed length of string";
}

?>

输出 对于积极的情景集 $startlist = 3;

Array
(
    [0] => Poland
    [1] => USA
    [2] => England
    [3] => China
    [4] => Uruguay
    [5] => Spain
    [6] => Taiwan
    [7] => Monaco
)
China,Uruguay,Spain,Taiwan,Monaco

对于负面情景集 $startlist = 8;

Array
(
    [0] => Poland
    [1] => USA
    [2] => England
    [3] => China
    [4] => Uruguay
    [5] => Spain
    [6] => Taiwan
    [7] => Monaco
)
Start limit exceed length of string

您可以设置 limit 到 explode 函数(第 3 个参数)并获取结果数组的最后一项

$str = 'Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco';
echo $result = explode(',', $str, 3)[2]; //England,China,Uruguay,Spain,Taiwan,Monaco

来自doc

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

只是另一种方式作为一个函数,returns新列表如果可以返回新列表,否则returns false....

<?php

function formatList ( $l, $c, $s, $r )
{
    $s -= 1;

    $p = explode ( $c, $l );

    return ( $r + $s ) <= count ( $p ) ? implode ( $c, array_slice ( $p, $s, $r ) ) : FALSE;
}   

$list = 'Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco';

$split_on = ',';

$start_on = 3;

$return_total = 5;

echo formatList ( $list, $split_on, $start_on, $return_total ); // should be in a if(), just for example


?>

如果您想获得 5 件商品 England,China,Uruguay,Spain,Taiwan,您可以使用 explode in combination with array_slice 并为 offset 指定 2,为 length 指定 5。

例如:

$str = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$result = array_slice(explode(',', $str),2, 5)
print_r($result);

结果:

Array
(
    [0] => England
    [1] => China
    [2] => Uruguay
    [3] => Spain
    [4] => Taiwan
)

看到一个php demo

那么您也可以使用 implode 来获得示例中的结果:

echo implode(',', $result);
// England,China,Uruguay,Spain,Taiwan