PHP返回下一个和上一个数组项

时间:2017-02-22 00:01:14

标签: php arrays

我有以下简单数组和php

$my_array=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"purple","e"=>"yellow");


$match_key = array_search("blue",$my_array);
                echo $match_key;

我想创建两个变量,它们是$ match_key两侧的数组项。所以在上面的例子中,我试图最终得到......

$previous = 'green';
$next = 'purple';

解决这个问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

如果您无法更改阵列结构,可以通过"创建"来执行以下操作:一个新数组,原始数组的值,通过array_values()

$vals = array_values($my_array);
$match_key = array_search("blue", $vals);

echo "PREV: ". $vals [($match_key - 1)] . "\n";
echo "CURR: ". $vals[$match_key] ."\n";
echo "NEXT: ". $vals [($match_key + 1)] . "\n";

返回:

PREV: green
CURR: blue
NEXT: purple

现在您需要进行密钥处理/等,以确保代码不会丢失任何错误并以微妙的方式处理您的密钥。

有许多其他方法(inspired by this post)利用内置函数,虽然看起来需要更长时间才能处理:

$match_key = array_search("blue", $my_array);
// loop through and set the array pointer to the $match_key element
while (key($my_array) !== $match_key) next($my_array);

$current = $my_array[$match_key];
$prev = prev($my_array);
next($my_array); // set the array pointer to the next elem (as we went back 1 via prev())
$next = next($my_array);

返回上一个,当前和&接下来如下:

CURRENT:  blue
PREVIOUS: green 
NEXT:     purple

答案 1 :(得分:0)

使用array_values()是可行的方法。这将按照与原始数组相同的顺序创建一个新的索引数组。

然后,您可以使用返回数字索引的array_search()来搜索您的值。然后只有+1代表下一个,-1代表前一代。

当然,您可能需要验证您要搜索的值是否确实存在。如果是,请确保index+1index-1也存在,如果他们不在,则设置为null

这样的事情:

$my_val = 'blue';

$int_indexes = array_values($my_array); // store all values into integer indexed array

if ($index = array_search($my_val, $int_indexes)) { // don't set prev-next if value not found
    $prev = array_key_exists($index - 1, $int_indexes) ? $int_indexes[$index - 1] : null;
    $next = array_key_exists($index + 1, $int_indexes) ? $int_indexes[$index + 1] : null;
}

echo "previous: $prev" . '<br>';
echo "this: $my_val" . '<br>';
echo "next: $next";

给你结果:

//    previous:  green
//    this:      blue
//    next:      purple

如果您的搜索值在开头或结尾,不用担心,您只需获得null值。并且找不到您的搜索值,不用担心,您只能获得2 null个值。