array repeating results

Asked

Viewed 213 times

0

I don’t understand why my array is repeating the results, my loop to go through it is like this:

for ($i = 0; $i < count($estados); $i++) {
   foreach ($estados[$i] as $key => $valor) {
      echo "<option value='".$estados[$i]['cod_estados']."'>".$estados[$i]['nome']."</option>";
   }
}

This loop is displaying in select as follows:

ACRE
ACRE
ACRE
ACRE
ACRE
ACRE
ALAGOAS
ALAGOAS
ALAGOAS
ALAGOAS
ALAGOAS
ALAGOAS

etc....

Here is an example of how the array is:

Array
(
[0] => Array
    (
        [cod_estados] => 1
        [0] => 1
        [sigla] => AC
        [1] => AC
        [nome] => ACRE
        [2] => ACRE
    )

[1] => Array
    (
        [cod_estados] => 2
        [0] => 2
        [sigla] => AL
        [1] => AL
        [nome] => ALAGOAS
        [2] => ALAGOAS
    )

[2] => Array
    (
        [cod_estados] => 3
        [0] => 3
        [sigla] => AP
        [1] => AP
        [nome] => AMAPÁ
        [2] => AMAPÁ
    )

Maybe it is a silly mistake, but I am not able to understand, I saw that it is repeating once for each item of the internal array.

  • 2

    pq uses a for and within it a foreach? only the foreach must solve.

  • Not sure, the array is multidimensional.

  • 1

    But you’re using it as one-dimensional when you do something like $estados[$i]['cod_estados']

1 answer

2


Has a for in its code and foreach is specified $estados[$i] when only a foreach would solve. $valor is equivalently $estados[$i] then when it comes time to assemble the options just call him.

foreach ($estados as $valor) {
  echo "<option value='".$valor['cod_estados']."'>".$valor['nome']."</option>";
}

Browser other questions tagged

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