Friday 26 June 2015

Get all the unique numbers from two-dimensional array

PHP recursive function that returns a two-dimensional array with all the unique numbers from a two-level array with numbers.
This function is useful when you have an array with other arrays with numbers, and you want to get the child arrays with numbers that aren't in the other arrays.
For example, if you have the following array:
$arr = array(
  'n1'=>array(1, 2, 3),
  'n2'=>array(1, 20, 13),
  'n3'=>array(11, 22, 8),
  'n4'=>array(10, 22, 7)
);
The getUniqueNr() function presented in this page will return this array (remowing child arrays with numbers that are in other array):
$arr = array(
  'n1'=>array(1, 2, 3),
  'n3'=>array(11, 22, 8)
);

- Code of the function:
// recursive function that returns an array with the unique numbers from a two-dimensional array
// receives: $arr (two-level array with numbers)
// no need to pass: $arc (array to compare), and: $re (array with returned result)
function getUniqueNr($arr, $arc=array(), $re=array()) {
  // From: http://coursesweb.net/php-mysql/
  // if its the first call
  if(count($arr) > 0) {
    if(count($arc) == 0) {
      $arc = current($arr);
      $re[key($arr)] = $arc;
    }

    $x = 0;
    foreach($arr AS $k=>$arv) {
      if(!array_intersect($arc, $arv)) {
        if($x == 0) {
          $next_arc = $re[$k] = $arv;
          $x = 1;
        }
      }
      else unset($arr[$k]);
    }
    if(count($arr) > 1 && isset($next_arc)) {
      array_shift($arr);
      return getUniqueNr($arr, $next_arc, $re);
    }
    else return $re;
  }
}
- Example (test it yourself):
<?php
// recursive function that returns an array with the unique numbers from a two-dimensional array
// receives: $arr (two-level array with numbers)
// no need to pass: $arc (array to compare), and: $re (array with returned result)
function getUniqueNr($arr, $arc=array(), $re=array()) {
  // From: http://coursesweb.net/php-mysql/
  // if its the first call
  if(count($arr) > 0) {
    if(count($arc) == 0) {
      $arc = current($arr);
      $re[key($arr)] = $arc;
    }

    $x = 0;
    foreach($arr AS $k=>$arv) {
      if(!array_intersect($arc, $arv)) {
        if($x == 0) {
          $next_arc = $re[$k] = $arv;
          $x = 1;
        }
      }
      else unset($arr[$k]);
    }
    if(count($arr) > 1 && isset($next_arc)) {
      array_shift($arr);
      return getUniqueNr($arr, $next_arc, $re);
    }
    else return $re;
  }
}

// two-level array with numbers
$arr = array(
  'arr1' => array(2, 6),
  'arr2' => array(4, 10),
  'arr3' => array(2, 12),
  'arr4' => array(50, 63),
 'arr5' => array(45, 50)
);

$unique_nrs = getUniqueNr($arr);

// test
var_export($unique_nrs);

// Result: array (0=>arra ('arr1' => 2, 1 => 6), 'arr2'=>array(0 => 4, 1 => 10), 'arr4'=>array(0 => 50, 1 => 63))
?>

0 comments:

Post a Comment