I have an array like this
我有一个这样的数组
$a=["apple","ball","cat","dog","elephant","fish"]
I want to make a two new array like this from array $a . I want the things before dog stay in $b and i want items dog elephants and fish in another array $c
我想从数组$a中创建一个这样的两个新数组。在买狗之前,我想买b美元的东西,我想买狗狗狗,大象和鱼的东西
$b=["apple","ball","cat"]
$c=["dog","elephant","fish"]
I want to do this by using word "dog" not using value 4 . Is it possible ? I searched many array function but my brain stopped working . So can some one help me ?
我想通过使用单词“dog”来实现这一点,而不是使用值4。是可能的吗?我搜索了很多数组函数,但我的大脑停止工作了。那么有人能帮我吗?
2 个解决方案
#1
0
If you are okay with array_search function then it's simple. See the following approaches:
如果您对array_search函数没有问题,那么它很简单。看到下面的方法:
$arr = array("apple","ball","cat", "deer", "frog", "dog","elephant","fish");
$res = array_chunk($arr, array_search('dog', $arr));
$first = $res[0]; $last = $res[1];
print_r($first);
print_r($last);
$last = array_splice($arr, array_search('dog', $arr));
print_r($arr);
print_r($last);
#2
0
You can use the functions array_search
, array_splice
, and array_reverse
to accomplish this:
您可以使用函数array_search、array_splice和array_reverse来完成以下任务:
$a = array("apple","ball","cat","dog","elephant","fish");
$lastItems = array_slice( $a, array_search( 'dog', $a ) );
$firstItems = array_reverse( array_slice( array_reverse( $a ), array_search( 'dog', $a ) ) );
There may yet be a simpler approach. But using the array_reverse
method to reverse the array will help you get the elements sliced before the array_search
element without using inverse directional slicing.
也许还有一种更简单的方法。但是使用array_reverse方法反转数组将帮助您在array_search元素之前将元素切片,而不需要使用反向定向切片。
Also note that I changed your array initialization.
还要注意,我更改了数组初始化。
#1
0
If you are okay with array_search function then it's simple. See the following approaches:
如果您对array_search函数没有问题,那么它很简单。看到下面的方法:
$arr = array("apple","ball","cat", "deer", "frog", "dog","elephant","fish");
$res = array_chunk($arr, array_search('dog', $arr));
$first = $res[0]; $last = $res[1];
print_r($first);
print_r($last);
$last = array_splice($arr, array_search('dog', $arr));
print_r($arr);
print_r($last);
#2
0
You can use the functions array_search
, array_splice
, and array_reverse
to accomplish this:
您可以使用函数array_search、array_splice和array_reverse来完成以下任务:
$a = array("apple","ball","cat","dog","elephant","fish");
$lastItems = array_slice( $a, array_search( 'dog', $a ) );
$firstItems = array_reverse( array_slice( array_reverse( $a ), array_search( 'dog', $a ) ) );
There may yet be a simpler approach. But using the array_reverse
method to reverse the array will help you get the elements sliced before the array_search
element without using inverse directional slicing.
也许还有一种更简单的方法。但是使用array_reverse方法反转数组将帮助您在array_search元素之前将元素切片,而不需要使用反向定向切片。
Also note that I changed your array initialization.
还要注意,我更改了数组初始化。