tags:

views:

98

answers:

7

Hello, I have an array similar to {A,B,C,D,E,F,G,H}. I would like to be able to pick an index or entry and have the array be reordered. So say if i had a function

reorder('C');

It would return the array starting at C, with anything before this index added on to the end, so this example would give

{C,D,E,F,G,H,A,B}

Is there a function that already does this?

Thanks

EDIT: I used this in the end

$key = array_search($imgToShow, $imgList);      
$sliceEnd = array_slice($imgList, 0, $key);     
$sliceStart = array_slice($imgList, count($sliceEnd));      
$array = array_merge($sliceStart, $sliceEnd);
A: 

There isn't a function that does this but you can write a one-liner using array_splice()/array_slice() functions that would do this.

m1tk4
+1  A: 

Not natively.

You should use usort (http://www.php.net/manual/en/function.usort.php) with a custom callback function.

See this example in the previous url:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");
ign
A: 

as far as i know, there isn't a predefined function to do this. you could use array slice and array_splice to make such a function.

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

and array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.

definition : http://www.php.net/manual/en/function.array-splice.php

hope this helps

Raz
+7  A: 

What you can do is simple array shift magic. First order the array, if it's not already ordered, if it is, skip this step:

sort($array);

Then find the value you want to start order by:

$key = array_search('C', $array);

Then remove the portion of the array before the found key:

$slice = array_splice($array, 0, $key);

Then append the slice at the end of the array:

array_splice($array, count($array), 0, $slice);
reko_t
Did you even test that?
Gumbo
Actually no, was bit in a hurry, fixed the answer a bit now. :P
reko_t
A: 
function reorder ($val, $ar){
  $p=array_search($val, $ar);
  $l=count($ar);

  for($j=0;$j<$l;j++){
    $nar[$j]=$ar[fmod($p,$l)];
    $p+=1;
  }
  return $nar;
}
Jan Sahin
+3  A: 

You can use array_search to find the index of the corresponding value and then array_splice to remove the second part (index to end) from the end and put it in front of the first part (0 to index-1) of the array:

$arr = array('A','B','C','D','E','F','G','H');
if (($i = array_search('C', $arr)) !== false) {
    array_splice($arr, 0, 0, array_splice($arr, $i));
}
Gumbo
A: 
Yanick Rochon