Look for value in array with multilevel index or not

Asked

Viewed 31 times

0

I have 2 arrays:

One with the index cod multilevel and other non:

$array1 = array(
        0 => array("item" => 101010, "cod" => 70),
        1 => array("item" => 102010, "cod" => 80),
        2 => array("item" => 103010, "cod" => 90)
        );

$array2 = array(
        0 => array("item" => 104010, "cod" => array
            (0 => 70, 1 => 80, 2 => 90)),
        1 => array("item" => 105010, "cod" => 80),
        2 => array("item" => 106010, "cod" => 70)
        );

Printed:

Array
(
    [0] => Array
        (
            [item] => 101010
            [cod] => 70
        )

    [1] => Array
        (
            [item] => 102010
            [cod] => 80
        )

    [2] => Array
        (
            [item] => 103010
            [cod] => 90
        )

)
Array
(
    [0] => Array
        (
            [item] => 104010
            [cod] => Array
                (
                    [0] => 70
                    [1] => 80
                    [2] => 90
                )

        )

    [1] => Array
        (
            [item] => 105010
            [cod] => 80
        )

    [2] => Array
        (
            [item] => 106010
            [cod] => 70
        )

)

When I use the array_search with the array_column, he will not bring the value if it is multilevel:

foreach ($array1 as $key => $v) {
    echo '<br>';
    echo $v['item'] .' - '. array_search($v['cod'], array_column($array2,'cod'));
}

Exit:

101010 - 2
102010 - 1
103010 - 

Is there any native function that makes this search considering it is multilevel or not ?

If not, how could I treat ?

  • 1

    This, just adapt the logic of the anonymous function in array_filter.

  • @W.Faustino works with multidimensional or not, on the same filter ?

  • @Andersoncarloswoss works with the 2 structures with this array_filter ?

  • 1

    It’s doing the function to work. Something like "if it’s array, search with in_array, if not, check if it’s the same".

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.