Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP array_multisort函数对多维关联数组进行排序,该数组包含一些整数键_Php_Multidimensional Array - Fatal编程技术网

使用PHP array_multisort函数对多维关联数组进行排序,该数组包含一些整数键

使用PHP array_multisort函数对多维关联数组进行排序,该数组包含一些整数键,php,multidimensional-array,Php,Multidimensional Array,如果关联数组包含整数键,array_multisort会自动重置它们,因此我会丢失数据。这里有一个小例子。有什么解决办法吗 $products = array ( '777.777' => array('price' => 10, 'name' => 'a'), '777' => array('price' => 100, 'name' => 'b') ); $sort_fi

如果关联数组包含整数键,array_multisort会自动重置它们,因此我会丢失数据。这里有一个小例子。有什么解决办法吗

$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 => $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 ) ) 
试试这个

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

?>