开发者

Using PHP array_multisort function to sort multi-dimensional associative array, which contains some integer keys

开发者 https://www.devze.com 2023-03-04 13:33 出处:网络
If an associative array contains integer keys, array_multisort automatically resets them, so I\'m losing data. Here is a small example. Any solutions?

If an associative array contains integer keys, array_multisort automatically resets them, so I'm losing data. Here is a small example. Any solutions?

$products = array ( '777.777' => array('price' => 10, 'name' => 'a'),
                    '777' => array('price' => 100, 'name' => 'b')
                  );    

$sort_field     = 'price';
$destination    = SORT_ASC;
$sort_array = array();
foreach ($products as $productId =&g开发者_运维技巧t; $product) {
    $sort_array[$productId] = $product[$sort_field];
}       
array_multisort($sort_array, $destination, $products);
print_r($products); 
   // Array ( [777.777] => Array ( [price] => 10 [name] => a ) [0] => Array ( [price] => 100 [name] => b ) ) 


Try this out

<?php

    $products = array('777.777' => array('price' => 10, 'name' => 'a'),
                    '777' => array('price' => 100, 'name' => 'b')
                  );

    $products = subval_sort($products, 'price');

    function subval_sort($array, $subkey) {

        foreach ($array as $key => $value) {

            $newArray[$key] = $value[$subkey];
        }

        arsort($newArray);

        foreach ($newArray as $key => $value) {

            $finalArray[$key] = $array[$key];
        }

        return $finalArray;
    }

    var_dump($products);

?>

http://codepad.org/VgdGdWyQ

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号