0

I have a PHP array that looks like this,

[["a","b"],["e","j"],["a","s"]]

I need it to look like this,

[["a","b"],["e","j"]]

or this,

[["e","j"],["a","s"]]

I cannot have two inner arrays that contain the same "0" index. It does not matter which inner array is deleted as long as only one remains. How can I go through this array and remove inner arrays that contain the same "0" index?

Thanks!

2 Answers2

0

You could simply loop through the array with two loops. Let's say this is your data:

$data = array(
    array('a', 'b'),
    array('e', 'j'),
    array('a', 's'),
    array('a', 't'),
    array('c', 't'),
    array('a', 'h'),
    array('c', 'e'),
    array('f', 'g')
);

Then you go ahead and loop through everything, and unset it if it's the same value.

$count = count($data);
foreach($data as $index => $array){
    for($i=$index + 1; $i<$count; $i++)
        if(isset($array[0]) && isset($data[$i][0]) && $array[0] == $data[$i][0])
            unset($data[$i]);
}

The var_dump of $data after the loops would be:

array(4) {
  [0]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "e"
    [1]=>
    string(1) "j"
  }
  [4]=>
  array(2) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "t"
  }
  [7]=>
  array(2) {
    [0]=>
    string(1) "f"
    [1]=>
    string(1) "g"
  }
}
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
0
<?php 
$array = [["a","b"],["e","j"],["a","s"]];
$values = array();


foreach ($array as $key => $arrayChild) {
    foreach ($arrayChild as $val) {
        if (in_array($val, $values)) {
            unset($array[$key]);
        }
        $values[] = $val;
    }
}
print_r($array);
?>

Result:

Array ( 
   [0] => Array ( [0] => a [1] => b ) 
   [1] => Array ( [0] => e [1] => j ) 
)
Jorge Hess
  • 550
  • 2
  • 9