[英]PHP custom function for array sorting wth usort not working
我正在研究 magento 站點 php 代碼並嘗試使用 label ASC 對數組進行排序。 所以這些值應該按 label 排序。
我為此使用了usort function
但即使我使用 function output 也看不出任何差異。
前任-
//$info has the array values
/*which assigned like this
$info['options'][] = array(
'id' => $value['value_index'],
'label' => $value['label'],
'price' => $configurablePrice,
'oldPrice' => $this->_prepareOldPrice($value['pricing_value'], $value['is_percent']),
'products' => $productsIndex,
);
*/
排序 function 如下
usort($info['options'], function ($a,$b){
return strcmp($a['label'],$b['label']);
}
);
var_dump($info);
即使我排序或不數組顯示這個 output
var spConfig = new Product.Config(array(10) {
[0]=>
array(5) {
["id"]=>
string(5) "46050"
["label"]=>
string(3) "110"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95331"
}
}
[1]=>
array(5) {
["id"]=>
string(5) "46071"
["label"]=>
string(3) "120"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95332"
}
}
[2]=>
array(5) {
["id"]=>
string(5) "46086"
["label"]=>
string(3) "130"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95333"
}
}
[3]=>
array(5) {
["id"]=>
string(5) "46112"
["label"]=>
string(3) "140"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95334"
}
}
[4]=>
array(5)
[6]=>
array(5) {
["id"]=>
string(5) "46455"
["label"]=>
string(2) "60"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95326"
}
}
[5]=>
array(5) {
["id"]=>
string(5) "46494"
["label"]=>
string(2) "70"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95327"
}
}
[5]=>
array(5) {
["id"]=>
string(5) "46527"
["label"]=>
string(2) "80"
["price"]=>
string(1) "0"
["oldPrice"]=>
string(1) "0"
["products"]=>
array(1) {
[0]=>
string(5) "95328"
}
}
}
我也嘗試了其他幾個數組鍵,但沒有一個不起作用,任何人都可以幫我排序,謝謝
嘗試將它們轉換為整數,因為字符串比較與 integer 比較非常不同。 例如, 2
按字典順序排在100
之后,但這不是您想要的。
usort ($info['options'], function ($a,$b) {
$la = intval($a['label']);
$lb = intval($b['label']);
if ($la < $lb) return -1;
if ($la > $lb) return 1;
return 0;
}
);
從 PHP 7 開始,可以直接使用 spaceship 算子,
usort ($info['options'], function ($a,$b) {
return intval($a['label']) <=> intval($b['label']);
}
);
從此更改您的usort
實現的第一個參數...
usort($info['label'], function ($a,$b){
return strcmp($a['label'],$b['label']);
}
對此...
usort($info['options'], function ($a,$b){
return strcmp($a['label'],$b['label']);
}
您只是使用了錯誤級別的數組進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.