Welcome Guest, Not a member yet? Register   Sign In
Finding an item's position in an array, and then returning previous and next items
#1

[eluser]Daniel H[/eluser]
Guys,

I wonder if anyone can explain how I can do this presumably straight forward thing.

Consider an array like this, e.g.

Code:
Array
(
    [0] => Array
        (
            [WorkExampleID] => 27947
            [Filename] => d9645d79046ca841a2b87e264b26b2fd.jpg
        )

    [1] => Array
        (
            [WorkExampleID] => 27946
            [Filename] => b9b8afc7a0814f890c5d66c1cd9ba591.gif
        )

    [2] => Array
        (
            [WorkExampleID] => 27945
            [Filename] => c3d8a8e538fb9d5de07c2353e2809b71.jpg
        )

    [3] => Array
        (
            [WorkExampleID] => 27944
            [Filename] => acebd1c4c45664048c7094e2267185aa.jpg
        )


On a page, I'm displaying work example whose ID is 27946, i.e. key[1]. How then would I firstly locate this value in the array, and then return ID 27945 (next) and ID 27947 (previous)?

Many thanks,

Dan.
#2

[eluser]xwero[/eluser]
from php.net array_search comments
Code:
function fktMultiArraySearch($arrInArray,$varSearchValue){
  
    foreach ($arrInArray as $key => $row){
        $ergebnis = array_search($varSearchValue, $row);
      
        if ($ergebnis){
            $arrReturnValue[0] = $key; // i would return the key
            $arrReturnValue[1] = $ergebnis; // i would remove this
            return $arrReturnValue;
        }
    }
}
With the key you can do
Code:
function surrounding_rows($array,$key)
{
   $return = array();
   if($key > 0)
   {
      $return['prev'] = $array[$key-1];
   }
  
   if($key+1 < count($array))
   {
     $return['next'] = $array[$key+1];
   }

   return $return;
}
which results in following code
Code:
$rows = surrounding_rows($files,fktMultiArraySearch($files,27946));
if(isset($rows['prev']))
{
    $previous_id = $rows['prev']['WorkExampleID'];
}
if(isset($rows['next']))
{
    $next_id = $rows['next']['WorkExampleID'];
}
#3

[eluser]Daniel H[/eluser]
That works beautifully - thank you so much for helping.




Theme © iAndrew 2016 - Forum software by © MyBB