My array looks like this:
Array (
[0] => Array
(
[id] => 613
[kleur] => royalblauw/wit
[maat] => maat XL
[voorraad] => 100
[sort] => 0
[prijs] => 4.1320
)
[1] => Array
(
[id] => 614
[kleur] => royalblauw/wit
[maat] => maat XXL
[voorraad] => 100
[sort] => 1
[prijs] => 4.1320
)
[2] => Array
(
[id] => 620
[kleur] => zwart/wit
[maat] => maat XL
[voorraad] => 100
[sort] => 2
[prijs] => 4.1320
)
etc.etc.
What I want is to sort the array by 'maat' (size). As you can see there are multiple entries with same 'maat'.
This is what I have until now.
function cmp($a, $b)
{
$sizes = array(
"116" => 0,
"128" => 1,
"140" => 2,
"152" => 3,
"164" => 4,
"XXS" => 5,
"XS" => 6,
"S" => 7,
"M" => 8,
"L" => 9,
"XL" => 10,
"XXL" => 11,
"XXXL" => 12,
"XXXXL" => 13,
"XXXXXL" => 14
);
$asize = $sizes[$a];
$bsize = $sizes[$b];
if ($asize == $bsize) {
return 0;
}
return ($asize > $bsize) ? 1 : -1;
}
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
uasort($sorter, "cmp");
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
And calling the function aasort:
aasort($maatkleur_array,"maat");
You want to sort an array of arrays. The parent array don't have a (named) key. uasort perserves the key wich you don't want in your case so use usort in stead:
error_reporting(E_ALL);
ini_set('display_errors','on');
function cmp($a, $b)
{
$sizes = array('s'=>0,'m'=>'1','l'=>2,'xl'=>3);
if ($sizes[$a['maat']] == $sizes[$b['maat']]) {
return 0;
}
return ($sizes[$a['maat']] < $sizes[$b['maat']]) ? -1 : 1;
}
$input = array(
array('id'=>1,'kleur'=>'blauw','maat'=>'xl'),
array('id'=>2,'kleur'=>'blauw','maat'=>'m'),
array('id'=>1,'kleur'=>'blauw','maat'=>'s'),
array('id'=>2,'kleur'=>'blauw','maat'=>'m'),
array('id'=>3,'kleur'=>'blauw','maat'=>'l')
);
usort($input, "cmp");
print_r($input);