My friend asked me a PHP question, but I didn't know it. so I ran to ask you !! I am engaged in JAVA, but my friend asked me a PHP question. the content is as follows: PHPcode $ testArrarray (php & gt; array (author & gt; allen, price & gt; 40.) a friend asked me a PHP question. I couldn't, so I ran to ask you !!
I am engaged in JAVA, but my friend asked me a PHP question. the content is as follows:
PHP code
$testArr = array( 'php' => array( 'author' => 'allen', 'price' => 40, ), 'java' => array( 'author' => 'james', 'price' => 55, ), 'mysql' => array( 'author' => 'gates', 'price' => 30, ), 'html' => array( 'author' => 'bill', 'price' => 21, ));
How can I sort by price field ??
You can also use the library function !!
------ Solution --------------------
Well, you are engaged in JAVA and the most expensive.
PHP code
Uasort ($ testArr, create_function ('$ a, $ B', 'return $ a ["price"]> $ B ["price"]; '); // change the price in ascending order to <
------ Solution --------------------
PHP code
Array ('author' => 'Allen ', 'price' => 40,), 'Java' => array ('author' => 'James ', 'price' => 55,), 'mysql' => array ('author' => 'gates', 'price' => 30 ,), 'html' => array ('author' => 'Bill ', 'price' => 21,); function my_sort ($ a, $ B) {return $ a ['price']> $ B ['price'];} uasort ($ testArr, "my_sort"); print_r ($ testArr);?>
------ Solution --------------------
PHP code
Foreach ($ testArr as $ v) {$ k [] = $ v ['price'];} array_multisort ($ k, SORT_DESC, $ testArr ); print_r (array_slice ($ testArr, 0, 3 ));
------ Solution --------------------
There are two types of three methods used by several persons upstairs.
Comparison:
PHP code
$ TestArr = array ('php' => array ('author' => 'Allen ', 'price' => 40 ,), 'Java' => array ('author' => 'James ', 'price' => 55 ,), 'mysql' => array ('author' => 'gates', 'price' => 30 ,), 'html' => array ('author' => 'Bill ', 'price' => 21 ,)); /*** application callback function ***/function func1 ($ ar) {uasort ($ ar, create_function ('$ a, $ B ', 'return $ a ["price"]> $ B ["price"]; '); // The price is in ascending order, in descending order, change to <}/*** do not use the callback function ***/function func2 ($ ar) {foreach ($ ar as $ key => $ row) {$ price [$ key] = $ row ['price'];} array_multisort ($ price, SORT_ASC, $ ar );} /*** application php5.3 closure ***/function func3 ($ ar) {array_multisort (array_map (function ($ v) {return $ v ['price'];}, $ ar), $ ar);} check_speed (200, 'function2', $ testArr); check_speed (200, 'func3', $ testArr); check_speed (200, 'function1', $ testArr );