I have an array that results in something like this: a = laranja b = banana c = maçã d = limao
Now I want to reorder it, but there is not something logical, like, d,c,b,a. I want to just reorder the way i want. could be a,d,c,b or , c,a,b,d.
I tried sort, multisort, but without sucess.
Are there some advice?
I paste some code here to see if its helps
See sort()
$yourArray;
sort($yourArray);
print_r($yourArray);
// Now alphabetical
Also if you write a function to sort the values however you want, use usort()
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value
";
}
?>
0: 1
1: 2
2: 3
3: 5
4: 6
Edit:
Your foreach statement is kaput.
<?php
function cmp($a, $b)
{
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array("d"=>"limao", "a"=>"laranja", "b" =>"banana", "c"=>"maçã");
print_R($a);
usort($a, "cmp");
print_R($a);
?>
Output:
Array
(
[d] => limao
[a] => laranja
[b] => banana
[c] => maçã
)
Array
(
[0] => banana
[1] => laranja
[2] => limao
[3] => maçã
)
You would probably need to add another entry in the array called something like sort_order
which has a numeric weight, and sort by that.
Like:
Array (
Array ( 'name' => 'test', 'sort' => 1 ),
Array ( 'name' => 'test test', 'sort' => 2 )
);