PHP返回下一个和上一个数组项
我有以下简单的数组和phpPHP返回下一个和上一个数组项,php,arrays,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 = 'g
$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';
解决此问题的最佳方法是什么?如果无法更改数组结构,可以通过以下方式“创建”一个新数组,只使用原始数组的值 返回:
PREV: green
CURR: blue
NEXT: purple
现在,您需要执行key handling/etc以确保代码不会抛出任何错误,并以一种微妙的方式处理密钥
还有其他各种方法()利用内置函数,尽管处理过程似乎需要更长的时间:
$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
使用array\u values()
是一种方法。这将按照与原始数组相同的顺序创建一个新的索引数组
然后,您可以使用返回数值索引的array\u search()
来搜索您的值。然后,下一个为+1,上一个为-1
当然,您可能需要验证正在搜索的值是否确实存在。如果是,则确保index+1
和index-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";
如果您搜索的值在开头或结尾,不用担心,您只会得到一个
null
值。如果没有找到您搜索的值,不用担心,您只会得到2个null
值。我建议使用min和max来限制下一个和上一个键,并使用array_值来确保数组始终是0索引的。@Rob同意,尽管我将答案留给了问题的范围。我们看看他会带什么回来
$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