After sorting the PHP array, keep the corresponding string key name-PHP source code

Source: Internet
Author: User
After the PHP array is sorted, the corresponding string key name is retained to [1] [full screen preview]
 
 "Lemon", "orange" => "orange", "banana" => "banana", "apple" => "apple", "blueberry" => "blueberry ", "strawberry" => "strawberry", "mango" => "mango", "durian" => "durian", "watermelon" => "watermelon ", "pear", "grape" => "grape"); foreach ($ fruits as $ key => $ val) // output the original array $ fruits echo "fruits [". $ key. "] = ". $ val."
"; Echo" "; // Call the sort_with_keyName () method to obtain the sorted array $ fruits_sorted = sort_with_keyName ($ fruits); // output the final result. Foreach ($ fruits_sorted as $ key => $ val) echo "fruites sorted [". $ key. "] =". $ val ."
";/* Defines a sorting method for the array $ arr and * retains the corresponding string key name (subscript) */function sort_with_keyName ($ arr) {// Copy the array foreach ($ arr as $ key => $ value) with the same content as $ arr in another place in the memory $ a $ key = $ value; sort ($ arr); // sort the array $ arr/* create an array * array $ B with the original array key name element value (key value, its element (key value) order is consistent with the sorted array $ arr. */$ Index = 0; foreach ($ arr as $ keys => $ values) // sort by the order of the sorted array foreach ($ a as $ key => $ value) // search for the key value if ($ values = $ value) in the backup array // if the key value $ B [$ index ++] = $ key; // Set the element value of array $ B to the key name of the backup array $ a // The return value uses the key value of array $ B as the key name, return array_combine ($ B, $ arr); };?>

2.[Image]Array_With_String_Keys.png

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.