PHP's corresponding operation for a two-dimensional array

Source: Internet
Author: User
This article mainly introduces PHP for the two-dimensional array of the corresponding operation, interested in the reference of friends, I hope to be helpful to everyone.

Tips Tips:

Array_keys ($array)//Returns all key names  array_values ($array)//Returns all key values   $result =array_reverse ($input);//reverses the array without preserving the key name $ Result_keyed=array_reverse ($input, true); Reverses the array, retains the key name  Array_keys ($array, "blue");//return value is the key name of Blue

1. PHP Two-dimensional array deduplication function
PHP array de-duplicates have a built-in function array_unique (), but PHP's Array_unique function only applies to one-dimensional arrays, not for multidimensional arrays, the following provides a two-dimensional array of array_unique functions

function Unique_arr ($array, $stkeep =false, $ndformat =true) {   //determines whether to preserve the first-level array key (the first-level array key can be non-numeric)   if ($stkeep) $ STARR = Array_keys ($array 2D);    Determines whether to preserve the two-level array key (all two-level array keys must be the same)   if ($ndformat) $NDARR = Array_keys (end ($array 2D));    Dimensionality, you can also convert a one-dimensional array to a comma-concatenated string   foreach ($array 2D as $v) {     $v = join (",", $v) using implode;      $temp [] = $v;   }    Remove the duplicated string, which is a repeating one-dimensional array   $temp = Array_unique ($temp);     Re-assemble the disassembled array   foreach ($temp as $k + $v)   {     if ($stkeep) $k = $STARR [$k];     if ($ndformat)     {       $TEMPARR = explode (",", $v);        foreach ($tempArr as $ndkey = $ndval) $output [$k] [$NDARR [$ndkey]] = $ndval;     }     else $output [$k] = Explode (",", $v);    }    return $output; }


$array 2D = Array (' First ' =>array (' title ' = ' 1111 ', ' date ' = ' 2222 '), ' second ' =>array (' title ' = ' 1111 ', ' Date ' = ' 2222 '), ' third ' =>array (' title ' = ' 2222 ', ' date ' = ' 3333 '));   Print_r ($array 2D); Print_r (Unique_arr ($array 2d,true));

2. Sorting methods for two-D arrays
One-dimensional array sorting method:
Common functions:

function Printr ($arr) {   echo ' <pre> ';    Print_r ($arr);   Echo ' </pre><br> '; }

The First group: sort and Rsort , sorted by the order of the PHP array key values ASC and reverse desc, while destroying the index relationship of the original array-in fact, after dropping the index, re-establishes the 0-based numeric index.

$a = Array (' a ' =>1,2);  Sort ($a); PRINTR ($a);  Rsort ($a); PRINTR ($a);  /*array (   [0] = 1   [1] = 2)  Array (   [0] = 2   [1] = 1) */

The second set of functions: Asort and Arsort, These two functions are a bit more powerful, as long as they can preserve the original index relationship of the array, the above example of the sort and rsort with the two functions to replace each

$a = Array (' a ' =>1,2); Asort ($a); PRINTR ($a);   Arsort ($a); PRINTR ($a);  /* Array (   [A] = 1   [0] = 2)  Array (   [0] = 2   [A] = 1) */

The third set of PHP array sorting functions: Krsort and Ksort, these two are different from the above two groups, these two functions are to sort the key names.

$a = Array (' a ' =>1,2);  Ksort ($a); PRINTR ($a);   Krsort ($a); PRINTR ($a);  /* Array (   [0] = 2   [a] + 1)  Array (   [A] = 1   [0] = 2) */

Using a custom function to sort the PHP array, there are three functions:
Uasort uses a custom function to sort the key values of the PHP array and preserves the original index relationship.
Uksort uses a custom function to sort the key names of the PHP array and preserves the original index relationship.
Usort sorts the key values of the PHP array by using a custom function, and deletes the original index relationship, creating a new index from scratch.
Here is a two-dimensional sort :

/** * @package Bugfree * @version $Id: functionsmain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss EXP $ * * * Sort A  n two-dimension array by some level, and the use Array_multisort () function.  * * Sortarr ($Array, "Key1", "Sort_asc", "Sort_retular", "Key2" ...)  * @author Chunsheng Wang <wwccss@263.net> * @param array $ArrayData the array to sort.  * @param string $KeyName 1 The first item to sort by. * @param string $SortOrder 1 The order to sort by ("Sort_asc" | " Sort_desc ") * @param string $SortType 1 the Sort type (" Sort_regular "|" Sort_numeric "|"  Sort_string ") * @return array sorted array. */function Sortarr ($ArrayData, $KeyName 1, $SortOrder 1 = "Sort_asc", $SortType 1 = "Sort_regular") {if (!is_array ($      Arraydata)) return $ArrayData;   Get args number.   $ArgCount = Func_num_args ();   Get keys to sort by and put them to sortrule array.     for ($I = 1; $I < $ArgCount; $I + +) {$Arg = Func_get_arg ($I); if (!eregi ("SORT", $Arg)) {$KeyNAmelist[] = $ARG;     $SortRule [] = ' $ '. $Arg;   } else $SortRule [] = $ARG;   }//Get The values according to the keys and put them to array. foreach ($ArrayData as $Key = $Info) {foreach ($KeyNameList as $KeyName) ${$KeyName}[$Key] = Strtolower ($Info [$Ke   Yname]);   }//Create the eval string and eval it.   $EvalString = ' Array_multisort ('. Join (",", $SortRule). ', $ArrayData);   eval ($EvalString); return $ArrayData; }

Instance:

################# example ################# $arr = Array (' name ' = ' learn ', ' size ' = ' 1235 ', ' t     Ype ' + ' jpe ', ' time ' = ' 1921-11-13 ', ' class ' + ' dd ', ', ' Array (' name ' = ' Chinese Kung Fu '), ' Size ' = ' 153 ', ' type ' = ' jpe ', ' time ' = ' 2005-11-13 ', ' class ' = ' JJ ', ' a '    Rray (' name ' = ' programming ', ' size ' = ' + ', ' type ' = ' gif ', ' time ' = ' 1997-11-13 ', ' Class ' = ' dd ', ', ' Array (' name ' = ' Chinese Kung fu ', ' size ' = ' + ', ' type ' = ' jpe ', ' t    IME ' = ' + ' 1925-02-13 ', ' class ' = ' yy ', ', ' Array (' name ' = ' Chinese Kung fu ', ' size ' = ' 5 ',  ' Type ' = ' icon ', ' time ' = ' 1967-12-13 ', ' class ' = ' rr ', '); Echo ' <pre> '; Print_r ($arr);  Echo ' <br> '; Note: Sort by number 153:65 small $temp = Sortarr ($arr, "name", "Sort_asc", "type", "Sort_desc", "size", "Sort_asc", "sort_string");  Print_r ($temp); Echo ' </pre> ';

3. Multidimensional array to one-dimensional array

function Rebuild_array ($arr) {//rebuild A array  static $tmp =array ();   for ($i =0; $i <count ($arr), $i + +) {   if (Is_array ($arr [$i])) {     Rebuild_array ($arr [$i]);   } else{     $tmp []= $arr [$i];   }  }   return $tmp; }

Instance:

$arr =array (' 123.html ', ' 456.html ', Array (' dw.html ', ' fl.html ', Array (' ps.html ', ' fw.html ')), ' ab.html ');  Define a three-dimensional array to detect our function echo ' <pre> '; Print_r (Rebuild_array ($arr)); Echo ' </pre> ';

4. Remove blank elements from the array

Function Array_remove_empty (& $arr, $trim = True)   {     foreach ($arr as $key = = $value) {       if (Is_array ($va Lue) {         array_remove_empty ($arr [$key]),       } else {         $value = trim ($value);         if ($value = = ") {           unset ($arr [$key]);         } elseif ($trim) {           $arr [$key] = $value;         }     }}   

Instance:

$a = Array (Array (3), 2, ' ', Array (', '), 0);  Array_remove_empty ($a);  PRINTR ($a); Printr function Please find in this article

5. Get the value under a specific key under a multidimensional array and generate a one-dimensional array

function Getall_by_key (array $arr, $key) {   if (!trim ($key)) return false;   Preg_match_all ("/\" $key \ "; \w{1}:(?: \ d+:|) (. *);/", Serialize ($arr), $output);   return $output [1];  S is a Test ")));  Printr (Getall_by_key ($TESTARR, ' out '));

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Related Article

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.