Skip to content
Advertisement

array_unique for multidimensional arrays

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:

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…

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));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement