简体   繁体   English

在PHP中的许多数组元素之间连接

[英]Concatenate some Array Elements among many in PHP

I have an array "$abc" which has 9 elements, as:- 我有一个数组“ $ abc”,其中包含9个元素,例如:

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. 现在,我只需要连接从“ b”索引到“ e”索引的4个元素。 But I don't know what to do. 但是我不知道该怎么办。 I used the "implode()" function of PHP in cases where all the array elements are concatenated. 在所有数组元素都连接在一起的情况下,我使用了PHP的“ implode()”函数。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

You need to extract the desired values first and then use implode . 您需要先提取所需的值,然后使用implode You could use array_slice : 您可以使用array_slice

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

That would produce went up the hill . 那将产生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'))));
$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;

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

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