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!

0

2 Answers 2

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"
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the help. Your answer works but how do I remove the numeric index keys when using json_encode to output the answer? {"0":["a","b"],"2":["c","e"]} I want to get rid of the "0" and "2"
@linuxisthebest33 What do you want it to be? Do you want it to be "0" and "1"?
I want the array to be returned as a standard indexed array like this [["a","b"],["e","g"]]
You could do json_encode(array_values($data)) to remove the indexes when you turn it into a json.
Thanks! Worked perfectly
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 ) 
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.