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. But I don't know what to do. I used the "implode()" function of PHP in cases where all the array elements are concatenated.
现在我只需要将从“b”索引开始的4个元素连接到“e”索引。但我不知道该怎么做。在所有数组元素连接的情况下,我使用了PHP的“implode()”函数。
Any help is greatly appreciated.
任何帮助是极大的赞赏。
2 个解决方案
#1
3
You need to extract the desired values first and then use implode
. You could use array_slice
:
您需要先提取所需的值,然后使用implode。你可以使用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'))));
#2
1
$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;
#1
3
You need to extract the desired values first and then use implode
. You could use array_slice
:
您需要先提取所需的值,然后使用implode。你可以使用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'))));
#2
1
$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;