matrix.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /*
  3. Copyright (c) 2009-2014 F3::Factory/Bong Cosca, All rights reserved.
  4. This file is part of the Fat-Free Framework (http://fatfree.sf.net).
  5. THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
  6. ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  7. IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  8. PURPOSE.
  9. Please see the license.txt file for more information.
  10. */
  11. //! Generic array utilities
  12. class Matrix extends Prefab {
  13. /**
  14. * Retrieve values from a specified column of a multi-dimensional
  15. * array variable
  16. * @return array
  17. * @param $var array
  18. * @param $col mixed
  19. **/
  20. function pick(array $var,$col) {
  21. return array_map(
  22. function($row) use($col) {
  23. return $row[$col];
  24. },
  25. $var
  26. );
  27. }
  28. /**
  29. * Rotate a two-dimensional array variable
  30. * @return NULL
  31. * @param $var array
  32. **/
  33. function transpose(array &$var) {
  34. $out=array();
  35. foreach ($var as $keyx=>$cols)
  36. foreach ($cols as $keyy=>$valy)
  37. $out[$keyy][$keyx]=$valy;
  38. $var=$out;
  39. }
  40. /**
  41. * Sort a multi-dimensional array variable on a specified column
  42. * @return bool
  43. * @param $var array
  44. * @param $col mixed
  45. * @param $order int
  46. **/
  47. function sort(array &$var,$col,$order=SORT_ASC) {
  48. uasort(
  49. $var,
  50. function($val1,$val2) use($col,$order) {
  51. list($v1,$v2)=array($val1[$col],$val2[$col]);
  52. $out=is_numeric($v1) && is_numeric($v2)?
  53. Base::instance()->sign($v1-$v2):strcmp($v1,$v2);
  54. if ($order==SORT_DESC)
  55. $out=-$out;
  56. return $out;
  57. }
  58. );
  59. $var=array_values($var);
  60. }
  61. /**
  62. * Change the key of a two-dimensional array element
  63. * @return NULL
  64. * @param $var array
  65. * @param $old string
  66. * @param $new string
  67. **/
  68. function changekey(array &$var,$old,$new) {
  69. $keys=array_keys($var);
  70. $vals=array_values($var);
  71. $keys[array_search($old,$keys)]=$new;
  72. $var=array_combine($keys,$vals);
  73. }
  74. /**
  75. * Return month calendar of specified date, with optional setting for
  76. * first day of week (0 for Sunday)
  77. * @return array
  78. * @param $date string
  79. * @param $first int
  80. **/
  81. function calendar($date='now',$first=0) {
  82. $parts=getdate(strtotime($date));
  83. $days=cal_days_in_month(CAL_GREGORIAN,$parts['mon'],$parts['year']);
  84. $ref=date('w',strtotime(date('Y-m',$parts[0]).'-01'))+(7-$first)%7;
  85. $out=array();
  86. for ($i=0;$i<$days;$i++)
  87. $out[floor(($ref+$i)/7)][($ref+$i)%7]=$i+1;
  88. return $out;
  89. }
  90. }