亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按值對PHP中的數組進行排序?

如何按值對PHP中的數組進行排序?

PHP
慕村9548890 2023-05-26 09:24:18
如果有人可以幫助我,我將非常感激。我的代碼:$product_var_tpl = array(? ? ? ? ? ? ? ? ? ? ? ? 'name' => $product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : ''),? ? ? ? ? ? ? ? ? ? ? ? 'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false),? ? ? ? ? ? ? ? ? ? ? ? 'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),? ? ? ? ? ? ? ? ? ? ? ? 'quantity' => $product['quantity'],? ? ? ? ? ? ? ? ? ? ? ? 'reference' => $seller_name,? ? ? ? ? ? ? ? ? ? ? ? 'customization' => array()? ? ? ? ? ? ? ? ? ? );我想按字母順序按“參考”對這個數組進行排序。我試過這個:usort($product_var_tpl, function($a, $b) {? ? return $a['reference'] - $b['reference'];});但結果為 null 或空。默認情況下輸出是:Referance? ? ?|? ?Product name | Unite price |? Qty? |? Pricetestshop2? ? ?|? ?pere? ? ? ? ?| 42,00? ? ? ?|? 0.5? | 21,00?testshoptwo? ?|? ?portocale? ? | 21,00? ? ? ?|? 1? ? | 21,00? ? ?irinatestshop |? ?qiwi? ? ? ? ?| 34,00? ? ? ?|? 0.5? | 17,00?irinatestshop |? ?Banane? ? ? ?| 12,00? ? ? ?| 1? ? ?| 12,00?如果我使用“usort”,我只會得到 4 個空行
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

請排序$product_var_tpl_list,不是$product_var_tpl。


以下是示例代碼。


$array = array(       // $product_var_tpl_list

        array(        // $product_var_tpl 1

            'name' => 'b',

            'reference' => 'bbb'

            ),

        array(        // $product_var_tpl 2

            'name' => 'a',

            'reference' => 'aaa'

            ),

        array(        // $product_var_tpl 3

            'name' => 'd',

            'reference' => 'ddd'

            ),

        array(        // $product_var_tpl 4

            'name' => 'c',

            'reference' => 'ccc'

            ),

        array(        // $product_var_tpl 5

            'name' => 'e',

            'reference' => 'eee'

            ),

        array(        // $product_var_tpl 6

            'name' => 'a',

            'reference' => 'www'

            )

    );


usort($array, function($a, $b) {

    return strcmp($a['reference'], $b['reference']);

});


print_r($array);

測試結果如下。


Array

(

    [0] => Array

        (

            [name] => a

            [reference] => aaa

        )


    [1] => Array

        (

            [name] => b

            [reference] => bbb

        )


    [2] => Array

        (

            [name] => c

            [reference] => ccc

        )


    [3] => Array

        (

            [name] => d

            [reference] => ddd

        )


    [4] => Array

        (

            [name] => e

            [reference] => eee

        )


    [5] => Array

        (

            [name] => a

            [reference] => www

        )


)


查看完整回答
反對 回復 2023-05-26
  • 1 回答
  • 0 關注
  • 158 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號