如何切片具有特定值的数组

时间:2015-10-29 10:28:12

标签: php

我有一个数组,我想在找到“Onsite”时切片。我试过切片功能没能用特定的词来实现。感谢您的帮助!

输出

 Array
(
    [0] => 1968
    [1] =>  ARNAVUTKÖY/İSTANBUL ŞUBESİ
    [2] => 212 597-0461
    [3] => 212 597-0075
    [4] => Arnavutköy
    [5] => İSTANBUL
    [6] => Arnavutköy Merkez Mah. Necip Fazıl Cd. No: 16 / 1 34275 Arnavutköy İstanbul 
    [7] => 41.18437
    [8] => 28.74354
    [9] => Onsite
    [10] => 1008
    [11] =>  HADIMKÖY/İSTANBUL ŞUBESİ
    [12] => 212 771-2177
    [13] => 212 771-2340
    [14] => Arnavutköy
    [15] => İSTANBUL
    [16] => Hadımköy Mah. Ayasofya Cd. No: 36 A / 1 34555 Arnavutköy İstanbul 
    [17] => 41.15646
    [18] => 28.61973
    [19] => Onsite
)

预期输出:

 Array
(
    [0] => 1968
    [1] =>  ARNAVUTKÖY/İSTANBUL ŞUBESİ
    [2] => 212 597-0461
    [3] => 212 597-0075
    [4] => Arnavutköy
    [5] => İSTANBUL
    [6] => Arnavutköy Merkez Mah. Necip Fazıl Cd. No: 16 / 1 34275 Arnavutköy İstanbul 
    [7] => 41.18437
    [8] => 28.74354
)

Array
    (
        [0] => 1008
        [1] =>  HADIMKÖY/İSTANBUL ŞUBESİ
        [2] => 212 771-2177
        [3] => 212 771-2340
        [4] => Arnavutköy
        [5] => İSTANBUL
        [6] => Hadımköy Mah. Ayasofya Cd. No: 36 A / 1 34555 Arnavutköy İstanbul 
        [7] => 41.15646
        [8] => 28.61973
)

2 个答案:

答案 0 :(得分:1)

请考虑以下事项:

$arr = array(1,2,3);
$slice_value = 2;
sliceByValue($arr, $slice_value);
function sliceByValue($arr, $val) {
    $index = array_search($val, $arr);
    $first = array_slice($arr, 0, $index);
    $second = array_slice($arr, $index+1, count($arr)-1);
    print_r($first);
    print_r($second);
}

放置arrayvalue并检查您是否获得了预期的输出。

答案 1 :(得分:0)

您可以使用array_search查找索引 - 如果该值不存在,则此函数返回false。这样做会产生以下结果:

$index = array_search('Onsite', $a);
if ($index !== false) {
    $first = array_slice($a, 0, $index);
    $second = array_slice($a, $index + 1);
}