PHP array sort

They have: 218 posts

Joined: Apr 2001

Hi there,

How can I re-sort this array, based on a user selection:

$listArray = array("Rooms", "Exterior", "Views");

// user selects "Rooms" which becomes the current value

$curVar = "Exterior";

How can I dynamically resort $listArray so "Exterior" is now the first element in the array?

Cheers,

TonyMontana
electricmountain.com

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

I'm lost.

They have: 218 posts

Joined: Apr 2001

Wink. If a current variable has the following value:

$curVar="Exterior";

How can I resort an array, such as:

$listArray = array("Rooms", "Exterior", "Views");

..so that "Exterior" (2nd array element) is now the first element in an array?

I'm looking for a php function that will make a comparison between two strings, ("Exterior" in this case), find a match, and then re-order the array accordingly.

Thanks,

Tony

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Try this....

<?php
if (!($key=array_search($curVal, $listArray))) {
   
$listArray = array_splice ($listArray, $key, 1);
   
$listArray = array_unshift($curVal);
}
?>

Mark Hensler
If there is no answer on Google, then there is no question.

They have: 218 posts

Joined: Apr 2001

Hmmm...that didn't work. Here's a twist, this a quick and dirty example in actionscript/javascript that works with what I'm trying to accomplish:

<?php
// user defined function for 'array.sort(userFunction)'

function compare(el){
    for (
i=0;i<listArray.length;i++){
        if (
listArray[i]==el){
         
listArray.unshift(listArray.splice(i, 1));
            
trace (listArray[0]); // value is whatever current match is...
            
trace (listArray[2]);
             }
        }
  }
                 
// triggered by button actions: curVal becomes one of the items from listArray()

function sortie(){
 
listArray = array(\"Exterior\", \"Rooms\", \"Views\");
      listArray.sort(compare(curVal));
}
?>

That's the idea of what I'm trying to translate to PHP.

Thanks,

Phil

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

I had some errors... try this:

<?php
if (!($key=array_search($curVal, $listArray))) {
   
array_splice($listArray, $key, 1);
   
array_unshift($listArray, $curVal);
}
?>

Mark Hensler
If there is no answer on Google, then there is no question.

They have: 218 posts

Joined: Apr 2001

Mark,

Just tweeked this line from:

<?php
if (!($key=array_search($curVal, $listArray))) {
?>

to:

<?php
if ($key=array_search($curVal, $listArray)) {
?>

And it seems to work thus far.

Thanks,

Phil

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

*slap* Duh!

Glad you got it working finally.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.