在 PHP 中连接多个数组元素

发布于 2024-09-12 05:51:12 字数 343 浏览 3 评论 0原文

我有一个数组“$abc”,它有 9 个元素,如下所示: -

Array
(
    [a] => Jack
    [b] => went
    [c] => up
    [d] => the
    [e] => hill
    [f] => but
    [g] => never
    [h] => came
    [i] => back
)

现在我只需要连接从“b”索引到“e”索引的 4 个元素。但我不知道该怎么办。在连接所有数组元素的情况下,我使用了 PHP 的“implode()”函数。

非常感谢任何帮助。

I have an array "$abc" which has 9 elements, as:-

Array
(
    [a] => Jack
    [b] => went
    [c] => up
    [d] => the
    [e] => hill
    [f] => but
    [g] => never
    [h] => came
    [i] => back
)

Now I need to concat only the 4 elements starting from the "b" index to the "e" index only. But I don't know what to do. I used the "implode()" function of PHP in cases where all the array elements are concatenated.

Any help is greatly appreciated.

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

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

发布评论

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

评论(2

白鸥掠海 2024-09-19 05:51:12

您需要先提取所需的值,然后使用implode。您可以使用 array_slice

echo implode(" ", array_slice($abc, 1, 4));

这会产生上山

如果您需要使用文字键,则需要更有创意。在你的情况下,最好只是循环遍历数组并进行比较,但你也可以做一些奇特的事情:

echo implode(" ", array_intersect_key($abc, array_flip(range('b', 'e'))));

You need to extract the desired values first and then use implode. You could use array_slice:

echo implode(" ", array_slice($abc, 1, 4));

That would produce went up the hill.

If you need to work with the literal keys, you need to be a bit more creative. In your case it would probably best just to loop through the array and compare, but you can do something exotic also:

echo implode(" ", array_intersect_key($abc, array_flip(range('b', 'e'))));
硪扪都還晓 2024-09-19 05:51:12
$test = array ( 'a' => 'Jack',
                'b' => 'went',
                'c' => 'up',
                'd' => 'the',
                'e' => 'hill',
                'f' => 'but',
                'g' => 'never',
                'h' => 'came',
                'i' => 'back'
              );
$start = 'b';
$end = 'e';

$result = implode(' ',array_slice($test,array_search($start,array_keys($test)),array_search($end,array_keys($test))-array_search($start,array_keys($test))+1));
echo $result;
$test = array ( 'a' => 'Jack',
                'b' => 'went',
                'c' => 'up',
                'd' => 'the',
                'e' => 'hill',
                'f' => 'but',
                'g' => 'never',
                'h' => 'came',
                'i' => 'back'
              );
$start = 'b';
$end = 'e';

$result = implode(' ',array_slice($test,array_search($start,array_keys($test)),array_search($end,array_keys($test))-array_search($start,array_keys($test))+1));
echo $result;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文