我的数组看起来像这样:
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.
我想要的是按'maat'(大小)对数组进行排序。如您所见,有多个条目具有相同的'maat'。
我现在已经尝试了几个小时,但仍然不是一个好结果。当然,我也一直在关注Stackoverflow。这就是我现在所拥有的。
功能:
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;
}
调用函数aasort:
aasort($maatkleur_array,"maat");
请你帮我。我希望很清楚我想要实现的目标。
答案 0 :(得分:2)
您想要对数组数组进行排序。父数组没有(命名)键。在你的情况下,uasort坚持你不想要的钥匙,所以请使用usort:
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);
答案 1 :(得分:1)
我已经改变了你的cmp功能,以达到你的目的..
$sort = array();
// $arrayData is your main array
foreach($arrayData as $key => $value)
{
$sort[$key] = cmp(strtoupper(str_replace('maat ', '', $value['maat'])));
}
array_multisort($sort, SORT_ASC, $arrayData);
function cmp($a)
{
$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
);
return $sizes[$a];
}
sort是基于cmp函数的返回值。 $ arrayData将根据maat大小排序数组。
答案 2 :(得分:-1)
编辑:
请改用此回调。这样就可以了:
<?php
function usort_callback($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
);
$value1 = $sizes[trim(str_replace('maat', '', $a['maat']))];
$value2 = $sizes[trim(str_replace('maat', '', $b['maat']))];
return ($value1 < $value2) ? -1 : 1;
}
?>
原始邮件:
使用usort()尝试:
<?php
function usort_callback($a, $b) {
return strcmp($a['maat'], $b['maat']);
}
usort($array, "usort_callback");
?>
现在你的数组应该按“maat”键
排序