I have more than 4 arrays in single variable as shown below
$myArray = Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas ) Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas )
Now i need to compare each and every array of [2] index.
If second index ([2] => USA) is present in some other array then delete duplicate array.
Finally the arrays should look like this
Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas ).
I have tried this but not able to sort it out.
$myArray = array_map("unserialize", array_unique(array_map("serialize", $myArray)));
Is there any way?
You can use a foreach
loop for this, like DEMO:
$match = [];
foreach($myArray as $key => $value)
{
if(!in_array($value[2], $match))
{
$match[] = $value[2];
continue;
}
unset($myArray[$key]);
}
This will remove all of the arrays which have duplicate value for [2]
You need to iterate through your array with two loops and check the second index value in each of the inner arrays and if there is a duplicated value you can just unset the second one.
Here is a piece of code that should do well:
<?php
for($i=0; $i < count($myArray); $i++) {
for($j=$i+1; $j < count($myArray); $j++) {
if ($myArray[$i][2] == $myArray[$j][2]) {
unset($myArray[$j][2]);
}
}
}
P.S: The code is not tested and may need some modifications, but you could get the main idea.