Difficulty finding values in an array

Asked

Viewed 29 times

1

The following code is an increment code in an array.

However, I haven’t been able to select any array value. If so print_r in it, it shows all but if I try to access with $guarda_array[1] he returns Array and not the name I want. Some part of the code is wrong?

$guarda_array = array();
$count_pub=mysqli_query($db, "SELECT nome FROM publicidades_sponsors");
$count_tudo=mysqli_num_rows($count_pub);
while($gu=mysqli_fetch_assoc($count_pub)){
    array_push($guarda_array, $gu);
}

The print_r shows the following

Array ( [0] => Array ( [nome] => DIDAXIS1.png ) [1] => Array ( [nome] => DIDAXIS2.png ) [2] => Array ( [nome] => DIDAXIS3.png ) [3] => Array ( [nome] => DIDAXIS4.png ) ) 
  • what it looks like when you from print_r?

  • Shows all array values

  • Right, but how is this result?

  • Array ( [0] => Array ( [name] => DIDAXIS1.png ) [1] => Array ( [name] => DIDAXIS2.png ) [2] => Array ( [name] => DIDAXIS3.png ) [3] => Array ( [name] => DIDAXIS4.png ) )

  • 1

    Is not array_push($guarda_array, $gu["nome"]) that you wanted to do?

  • @Pagotti Exactly! Post as answer I will accept when you can

Show 1 more comment

2 answers

1

The structure of your array is like this:

Array ( 
    [0] => Array ( 
        [nome] => DIDAXIS1.png 
    ) 
    [1] => Array ( 
        [nome] => DIDAXIS2.png 
    ) 
    [2] => Array ( 
        [nome] => DIDAXIS3.png 
    ) 
    [3] => Array ( 
        [nome] => DIDAXIS4.png 
    ) 
)

Then realize your attempt misses:

$guarda_array[1]

That one $guarda_array[1] has as content an array, so it returned array, to catch the nome inside $guarda_array[1]:

$guarda_array[1]['nome']

1


If the intention is to have as a result array with the field "name" of SELECT, you need to do:

$guarda_array = array();
$count_pub=mysqli_query($db, "SELECT nome FROM publicidades_sponsors");
$count_tudo=mysqli_num_rows($count_pub);
while($gu=mysqli_fetch_assoc($count_pub)){
    array_push($guarda_array, $gu["nome"]);
}

Browser other questions tagged

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