PHP array sort
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 posted this at 18:14 — 3rd July 2003.
He has: 4,048 posts
Joined: Aug 2000
I'm lost.
TonyMontana posted this at 18:26 — 3rd July 2003.
They have: 218 posts
Joined: Apr 2001
. 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 posted this at 19:53 — 3rd July 2003.
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.
TonyMontana posted this at 22:02 — 3rd July 2003.
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 posted this at 00:22 — 4th July 2003.
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.
TonyMontana posted this at 03:18 — 4th July 2003.
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 posted this at 07:44 — 4th July 2003.
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.