我有一个数组:
array(a,b,c,d,e,f,g,h,i,j);
我希望传递一封信并在其中任何一方收到信件。例如。 'f'将是'e'和'g'。
有一种简单的方法可以做到这一点。
另外,如果我选择'a',我会想要一个响应null和'b'。
这是我的实际数组,数组搜索如何使用多维数组?
array(19) { [0]=> array(3) { ["id"]=> string(2) "46" ["title"]=> string(7) "A" ["thumb"]=> string(68) "013de1e6ab2bfb5bf9fa7de648028a4aefea0ade816b935dd423ed1ce15818ba.jpg" } [1]=> array(3) { ["id"]=> string(2) "47" ["title"]=> string(7) "B" ["thumb"]=> string(68) "9df2be62d615f8a6ae9b7de36671c9907e4dadd3d9c3c5db1e21ac815cf098e6.jpg" } [2]=> array(3) { ["id"]=> string(2) "49" ["title"]=> string(6) "Look 7" ["thumb"]=> string(68) "0bfb2a6dd1142699ac113e4184364bdf5229517d98d0a428b62f6a72c8288dac.jpg" } etc etc...
答案 0 :(得分:4)
您可以使用array_search()
在数组中搜索给定值,并在成功时返回相应的键
<?php
$arr=array('a','b','c','d','e','f','g','h','i','j');
$key = array_search('a',$arr);
echo isset($arr[$key-1])?$arr[$key-1]:'NULL';
echo isset($arr[$key+1])?$arr[$key+1]:'NULL';
答案 1 :(得分:2)
这有效 -
function find_neighbour($arr, $value){
$index = array_search($value, $arr);
if($index === false){
return false;
}
if($index == 0){
return Array(null, $arr[1]);
}
if($index == count($arr)-1){
return Array($arr[$index-1], null);
}
return Array($arr[$index-1], $arr[$index+1]);
}
$a = Array('a','b','c','d','e','f','g','h','i','j');
print_r(find_neighbour($a,"a")); //[null, 'b']
print_r(find_neighbour($a,"j")); //['i', null]
print_r(find_neighbour($a,"e")); //['d', 'f']
答案 2 :(得分:0)
<?php
$arr=array("a","b","c","d","e","f","g","h","i","j");
function context($array,$element) {
return array(@$array[array_search($element,$array)-1],@$array[array_search($element,$array)+1]);;
}
print_r(context($arr,"a"));
print_r(context($arr,"e"));
print_r(context($arr,"j"));
输出:
Array
(
[0] =>
[1] => b
)
Array
(
[0] => d
[1] => f
)
Array
(
[0] => i
[1] =>
)
答案 3 :(得分:0)
数组搜索是一种可能性,如前所述,或者您可以通过for循环
运行var selection = 'a'; // your selection
var arr = [ 'a', 'b', 'c', 'd', 'e', 'f']; // small array
var i = 0, // define loop i
le = arr.length, // define loop length
out, // output var
match = ''; // matching data
before = 'non', // before data
after = 'non'; // after data
for(i; i < le; i++){ // run the loop
if(arr[i] === selection){ // if loop matches selection
match = arr[i]; // set match var
after = arr[i+1] || after; // set after var, if undifined, set "non" from above
before = arr[i-1] || before; // set before var if undefined, set "non" from above
}
}
out = 'match: ' + match + ' before: ' + before + ' after: ' + after; //build output
alert(out);