-1

I have this array. In this I want to skip the value for reverse data.

$data = array(
    array(2, 1),
    array(1, 2),
    array(1, 2),
    array(2, 1),
    array(2, 3),
    array(3, 2),
    array(4, 5)
);

I want to skip the values:

array(1,2)
array(1,2)
array(2,1)
array(3,2)

And I want the result array to be like this:

array(
    array(2, 1),
    array(2, 3),
    array(4, 5)
);
Dan Belden
  • 1,199
  • 1
  • 9
  • 20
madhu
  • 114
  • 7
  • You mean you want to eliminate duplicate values, and then sort the array? Or you you mean simply remove individual values from the array? Can you explain what you mean by "skip" and what rules determine what elements are to be skipped? – Mark Baker Aug 08 '15 at 10:05
  • Yes, I want to eliminate the duplicate value as well as eliminate the reverse order of the array. – madhu Aug 08 '15 at 10:07
  • He wants to delete the duplicate sub-arrays, even if the elements in the sub-array are in a different order. Basically unique sub-arrays - keys not important. – Dan Belden Aug 08 '15 at 10:08

2 Answers2

2
$data = [[2,1], [1,2], [1,2], [2,1], [2,3], [3,2], [4,5]];

$data = array_map(
    function($value) {
        sort($value);
        return serialize($value);
    },
    $data
);

$data = array_unique($data);
$data = array_map('unserialize', $data);
array_walk($data, 'sort');

var_dump($data);

Demo

EDIT

As per arbogast's comment, this can be simplified even further, eliminating the serialize/unserialize steps:

$data = [[2,1], [1,2], [1,2], [2,1], [2,3], [3,2], [4,5]];

array_walk($data, 'sort');
$data = array_unique($data, SORT_REGULAR);

var_dump($data);

Demo

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Try this:

function filterArray($data)
{
      $result = array();
      array_push($result, $data[0]); //You can always add first item without performing any check
      for($i=1; $i<count($data); $i++)
      {
          $allowAdd = true;
          foreach($result as $res)
          {
              if(($res == $data[$i]) || ($res[0] = $data[$i][1] && $res[1] = $data[$i][0]))
              {
                  $allowAdd = false;
                  break;
              }
          }
          if($allowAdd)
            array_push($result, $data[$i]);
     }
     return $result;
}

Now, when you call filterArray($data), this will return you the filtered result.

hamed
  • 7,939
  • 15
  • 60
  • 114