In case of one-dim array I can use array_unique
to get unique entries. But which function should be used to work with two-dim arrays?
For instance:
JavaScript
x
Array[0][0] = '123'; Array[0][1] = 'aaa';
Array[1][0] = '124'; Array[1][1] = 'aaa';
Array[2][0] = '124'; Array[2][1] = 'aaa';
In the above example I need to delete non-unique rows based on column 0. As a result I should get first two entries, while the third entry should be deleted. How to do this?
Advertisement
Answer
Try this…
JavaScript
function unique_matrix($matrix) {
$matrixAux = $matrix;
foreach($matrix as $key => $subMatrix) {
unset($matrixAux[$key]);
foreach($matrixAux as $subMatrixAux) {
if($subMatrix === $subMatrixAux) {
// Or this
//if($subMatrix[0] === $subMatrixAux[0]) {
unset($matrix[$key]);
}
}
}
return $matrix;
}
$matrix = array(
0 => array(0 => '123', 1 => 'aaa'),
1 => array(0 => '124', 1 => 'aaa'),
2 => array(0 => '124', 1 => 'aaa'),
);
var_dump(unique_matrix($matrix));