Remove duplicate values of specific key in multidimensional array in PHP but remove the last?

Viewed 2013

I have an array like this

 Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

4 Answers

You can do this with a slight change in your code. Unset the second array '$my_arrays' and use it.

foreach ($my_array as $k => $v) {
    foreach ($my_arrays as $key => $value) {
        if ($k != $key && $v['clave'] == $value['clave']) {
           unset($my_arrays[$k]);
        }
    }
}

echo '<pre>';
print_r($my_arrays);
Related