Get the position of an Associative Array within another Array

Asked

Viewed 73 times

0

I have this array of associative array’s:

Array { 

    [0]=> array(4) { ["nome"]=> string(35) "ACRILEX TECIDO 37ML AMARELO CANARIO" 
                     ["preco"]=> string(4) "1.65" 
                     ["quantidade"]=> string(1) "1" 
                     ["imagem"]=> string(25) "Loja/imgPQ/4140589589.gif" } 

    [1]=> array(4) { ["nome"]=> string(35) "ACRILEX TECIDO 37ML AMARELO LIM�O" 
                     ["preco"]=> string(4) "1.65" 
                     ["quantidade"]=> string(1) "1" 
                     ["imagem"]=> string(25) "Loja/imgPQ/4140504504.gif" } }

And I wanted to go through it and when I found a name equal to one of the products that returned the position where this associative array is to access its quantity

  • The simplest is through foreach. Have you tried anything?

  • I already got through the foreach with key => value

  • Answers should be in the answer area, not the question.

1 answer

0


The simplest way to solve the problem is to walk the array checking the name of each position and, when finding the desired name, return it.

function getKeyFromName($array, $name) {
    foreach($array as $key => $value) {
        if ($value["nome"] == $name) {
            return $key;
        }
    }

    return false;
}

See working in Ideone | Repl.it

An alternative is to use the functions array_column and array_search together:

function getKeyFromName($array, $name) {
    return array_search($name, array_column($array, "nome"));
}

See working in Ideone | Repl.it

The result will be exactly the same.

Browser other questions tagged

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