找到位置并获得前后?

时间:2011-09-04 22:57:13

标签: php

$x = "P-29042011386693";
$array = "P-28042011135870,P-28042011132333,P-28042011384621,P-29042011386693,P-29042011384190,P-29042011388434,P-29042011382454,P-29042011385512,P-29042011383902";
$array = explode(",", $array);
$count = count($array);
$search = array_search($x, $array);

if (($search > 0) && ($search < $count)){
    $before = $array[$search-1];
    $after = $array[$search+1];
}elseif ($search == 0){
    $before = NULL;
    $after = $array[1];
}elseif ($search == $count){
    $before = $array[$count-1];
    $after = NULL;
}

检测$ x之前的值和$ x之后的值的最佳方法是什么,如果在$ x之前/之后没有结果,则将$ before或$ after显示为空白?

所以如果$ x是P-29042011383902 - $之后是空白而且之前的$将是P-29042011385512

如果$ x为P-28042011135870 $之前为空白且$ after之后为P-28042011132333

我的代码是否正确?

2 个答案:

答案 0 :(得分:1)

这样的东西?

$ eachone = explode(“,”,$ row);

6是$ eachone [6]

5是$ eachone [6-1]

如果我理解了这个问题,那就是它。

有了新信息:

php.net上的例子是:

$str = "Hello Friend"; 
$arr1 = str_split($str); and you get an array like this

Array
(
    [0] => H[1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

答案 1 :(得分:1)

$search = array_search($x, $array);
if (false === $search) {
    throw new Exception('Not found', 404);
}
$before = isset($array[$search - 1]) ? $array[$search - 1] : null;
$after  = isset($array[$search + 1]) ? $array[$search + 1] : null;