Advertisement
mate2code

Individually sorting subarrays of an array in PHP

Nov 3rd, 2014
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.03 KB | None | 0 0
  1. <?php
  2.  
  3. // http://stackoverflow.com/questions/26713294/individually-sorting-subarrays-of-an-array-in-php
  4. // $arr1 gives the expected result, $arr2 does not,
  5. // although array_walk() should do exactly the same as the foreach - apply sort() on all subarrays of $arr
  6.  
  7. $arr = array(
  8.     array( 1, 1, 1, 2 ),
  9.     array( 1, 2, array(1,1) ),
  10.     array( 1, 2, array(1,1) ),
  11.     array( 1, 2, array(1,1) ),
  12.     array( 2, array(1,1,1) ),
  13.     array( 1, 1, array(1,2) ),
  14.     array( array(1,2), array(1,1) ),
  15.     array( 1, 1, array(1,2) ),
  16.     array( array(1,1), array(1,2) ),
  17.     array( 1, array(1,1,2) ),
  18.     array( 1, 1, array(1,2) ),
  19.     array( array(1,1), array(1,2) ),
  20.     array( 1, array(1,1,2) ),
  21.     array( 1, array(1,1,2) ),
  22.     array( array(1,1,1,2) )
  23. );
  24. // 15 rows
  25.  
  26. $arr1 = $arr;
  27. foreach ($arr1 as $key => $val) {
  28.     $derp = $val;
  29.     sort($derp);
  30.     $arr1[$key] = $derp;
  31. }
  32. sort($arr1);
  33. $arr1 = array_map("unserialize", array_unique(array_map("serialize", $arr1)));
  34.  
  35. $arr2 = $arr;
  36. array_walk($arr2, 'sort');
  37. sort($arr2);
  38. $arr2 = array_map("unserialize", array_unique(array_map("serialize", $arr2)));
  39.  
  40. echo array_values($arr1) == array_values(array(
  41.     array( array(1,1,1,2) ),
  42.     array( 1, array(1,1,2) ),
  43.     array( 2, array(1,1,1) ),
  44.     array( array(1,1), array(1,2) ),
  45.     array( 1, 1, array(1,2) ),
  46.     array( 1, 2, array(1,1) ),
  47.     array( 1, 1, 1, 2 )
  48. ));
  49. // 7 rows
  50.  
  51. echo array_values($arr2) == array_values(array(
  52.     array( array(1,1,1,2) ),
  53.     array( 1, array(1,1,2) ),
  54.     array( 2, array(1,1,1) ),
  55.     array( array(1,1), array(1,2) ),
  56.     array( array(1,1,2), 1 ),
  57.     array( 1, 1, array(1,2) ),
  58.     array( 1, 2, array(1,1) ),
  59.     array( 1, array(1,1), 2 ),
  60.     array( 1, 1, 1, 2 )
  61. ));
  62. // 9 rows
  63. // array( 1, array(1,1), 2 )  is a duplicate of  array( 1, 2, array(1,1) )
  64. // array( array(1,1,2), 1 )  is a duplicate of  array( 1, array(1,1,2) )
  65.  
  66. // this script will display two ones for the equalities
  67. // and six times "Notice: Array to string conversion in ..." for the line that contains array_walk
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement