Skip to content
Advertisement

How to sort an Array in PHP by value?

I know that this is asked before, I even tryied to do as on this question: How to Sort Multi-dimensional Array by Value?

But in my case it doesn’t work. If anybody can help me I will be very thankful.

My code:

$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()

                    );

I want to sort this array by “reference” in alphabetical order.

I tried this:

usort($product_var_tpl, function($a, $b) {
    return $a['reference'] - $b['reference'];
});

But the result is null or empty.

By default the output is:

Referance     |   Product name | Unite price |  Qty  |  Price

testshop2     |   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 

If I use “usort” I only get 4 empty rows

This si the full code:

// Construct order detail table for the email
                    $products_list = '';
                    $virtual_product = true;

                    $product_var_tpl_list = array();
                    foreach ($order->product_list as $product) {
                        $price = Product::getPriceStatic((int)$product['id_product'], false, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 6, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                        $price_wt = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 2, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});

                        $product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;

                        //aici se pune date despre vinzaor
                        $idProduct = (int)$product['id_product'];
                        $SellerInfoOverride = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller_product`  WHERE `id_ps_product` = '.(int) $idProduct);
                        //print_r ($SellerInfoOverride);
                        foreach ($SellerInfoOverride as $key => $value) {
                            $sellerid = $value['id_seller'];
                            //$seller = $mpSeller->getSeller($value['id_seller'], $this->context->language->id);
                            $SellerInfoDetails = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller`  WHERE `id_seller` = '.(int) $sellerid);
                            foreach ($SellerInfoDetails as $key => $value) {
                                $seller_name = $value['shop_name_unique'];
                            }
                        }

                        $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'];
                        });

                        $customized_datas = Product::getAllCustomizedDatas((int)$order->id_cart);
                        if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                            $product_var_tpl['customization'] = array();
                            foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                                $customization_text = '';
                                if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                    foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                        $customization_text .= $text['name'].': '.$text['value'].'<br />';
                                    }
                                }

                                if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                    $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])).'<br />';
                                }

                                $customization_quantity = (int)$product['customization_quantity'];

                                $product_var_tpl['customization'][] = array(
                                    'customization_text' => $customization_text,
                                    'customization_quantity' => $customization_quantity,
                                    'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)
                                );
                            }
                        }

                        $product_var_tpl_list[] = $product_var_tpl;
                        // Check if is not a virutal product for the displaying of shipping
                        if (!$product['is_virtual']) {
                            $virtual_product &= false;
                        }
                    } // end foreach ($products)

Advertisement

Answer

Please sort $product_var_tpl_list, not $product_var_tpl.

Following is sample code.

$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);

And test result is as following.

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
        )

)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement