我仍然对如何按特定值排序数组感到困惑。我知道你应该使用CMD
函数和usort()
。然而,我只是对我想做的事感到困惑。我想对我的数组进行排序,以便按顺序显示“Bronze”,“Silver”,“Gold”,“Platinum”等键。我不确定如何将我需要的内容放入以下内容中:
function cmp($a, $b){
return strcmp(???);
}
所以基本上我有一个数组就是这样听:
"itemname" => "Value"
我希望整个事情按“价值”的价值排序。价值可能是“青铜”/“银”/“金”/“白金”。我希望按顺序排序。
编辑2
$query = "SELECT * FROM postallions WHERE userid = :userid";
$params = array(':userid' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
$postallionlist = $columns;
print_r($postallionlist);
function compareMedals( $a, $b ) {
$aMap = array(0 => 'None', 1 => 'Bronze', 2 => 'Silver', 3 => 'Gold', 4 => 'Platinum', 5 => 'Uncomplete', 6 => 'Complete');
$aValues = array( 0, 1, 2, 3, 4, 5, 6);
$a = str_ireplace($aMap, $aValues, $a);
$b = str_ireplace($aMap, $aValues, $b);
return $a - $b;
}
usort($postallionlist, 'compareMedals');
print_r($postallionlist);
编辑3 print_r然后是var_dump:
Array ( [userid] => 1 [0] => 1 [p1] => Silver [1] => Silver [p2] => Platinum [2] => Platinum [p3] => None [3] => None [p4] => None [4] => None [p5] => Bronze [5] => Bronze [p6] => Gold [6] => Gold [p7] => Complete [7] => Complete [p8] => None [8] => None [p9] => None [9] => None [p10] => None [10] => None )
array (size=22)
'userid' => string '1' (length=1)
0 => string '1' (length=1)
'p1' => string 'Silver' (length=6)
1 => string 'Silver' (length=6)
'p2' => string 'Platinum' (length=8)
2 => string 'Platinum' (length=8)
'p3' => string 'None' (length=4)
3 => string 'None' (length=4)
'p4' => string 'None' (length=4)
4 => string 'None' (length=4)
'p5' => string 'Bronze' (length=6)
5 => string 'Bronze' (length=6)
'p6' => string 'Gold' (length=4)
6 => string 'Gold' (length=4)
'p7' => string 'Complete' (length=8)
7 => string 'Complete' (length=8)
'p8' => string 'None' (length=4)
8 => string 'None' (length=4)
'p9' => string 'None' (length=4)
9 => string 'None' (length=4)
'p10' => string 'None' (length=4)
10 => string 'None' (length=4)
答案 0 :(得分:1)
将名称转换为您喜欢的位置。
这是一个工作原型:
$aMedals = array(
'adbv' => 'Gold',
'sdgg' => 'Bronze',
'dsgggsd' =>'Platinum',
'dsggsg' => 'Silver',
'34g434h34' => 'Bronze',
'g34h4h' =>'Platinum',
'g34h4h' =>'Gold',
'dsg34t43tgsg' => 'Silver'
);
var_dump( $aMedals );
function compareMedals( $a, $b )
{
$aMap = array( 0 => 'Bronze', 1 => 'Silver', 2 => 'Gold', 3 => 'Platinum');
$aValues = array( 0, 1, 2, 3 );
$a = str_ireplace( $aMap, $aValues, $a );
$b = str_ireplace( $aMap, $aValues, $b );
return $a - $b;
}
usort( $aMedals, 'compareMedals');
var_dump( $aMedals );
输出:
array(7) {
[0]=>
string(6) "Bronze"
[1]=>
string(6) "Bronze"
[2]=>
string(6) "Silver"
[3]=>
string(6) "Silver"
[4]=>
string(4) "Gold"
[5]=>
string(4) "Gold"
[6]=>
string(8) "Platinum"
}