I have an array:

array(a,b,c,d,e,f,g,h,i,j);

I wish to pass in a letter and get the letters either side of it. eg. 'f' would be 'e' and 'g'.

Is there an easy way to do this.

Also if I were to select 'a' I would want a response null and 'b'.

Here's my actual array, how would array search work with multidimensional array?

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...
有帮助吗?

解决方案

You could make use of array_search()

Searches the array for a given value and returns the corresponding key if successful

<?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';

Demo

其他提示

This works -

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']
<?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"));

output:

Array
(
    [0] => 
    [1] => b
)
Array
(
    [0] => d
    [1] => f
)
Array
(
    [0] => i
    [1] => 
)

Array Search is a posibility, as commented before, or you can run through an for loop

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); 

http://jsbin.com/qixu/3/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top