2013-07-03 32 views
0

如果我有以下格式的數組,我怎樣才能將這些數組的一部分賦值給一個新數組? (數值123654指示該陣列可在這些位置被分離)PHP獲取字符串的一部分到新的數組?

$fruits = array(); 
$vehicles = array(); 
$all_words = array ("123", "apple", 」orange」, ………, 」bannana」, 」123」, 」654」, 」car」, 」bus」, ………, 」train」, 」bike」, 」654」); 
//continuous ……… Indicate there can be unknown amount of array elements. 
//Also, these numeric values of 123 and 645 can be changed to something convenient 

我可以看到,使用$fruits = array_slice($array, 1, 5)我可以在向一個新得到這個陣列的一部分。但是,如果我不知道兩個數字(123654之間數組的長度,我怎麼能在一個新的數組分配這些價值觀?

+0

感謝您的詳細解答和評論。它幫助了很多。 –

回答

2

可以使用array_search()得到他們的指數,然後將它們用於切片,像這個..

$index1 = array_search('123', $all_words); 
$index2 = array_search('654', $all_words); 
$vehicles = array_slice($array, $index1, $index2-$index1+1); 
+0

沒有理由給予好評,你忘了+1各項指標,因爲'array_search'將返回' 0'在這個例子中,但'array_slice'需要'1' – vladkras

+0

好的,你做到了! – vladkras

0

$fruits = array_slice($array, array_search('123', $array)+1, array_search('654', $array)+1)