How can I make a select and turn it into array

1

Well, by the title of the question I could not explain very well what I wanted but here it goes in practice:

I have a select to a table called "posts".

This select wants me to indicate all posts, where the supervisor is the "Test".

After that I make a mysqli_fetch_array

And then I show the $ array ["post"];

However, it only shows me 1 post, and in fact the "Test" supervisor has more than one post.

How can I turn select posts into 1 array?

Thank you.

    
asked by anonymous 22.01.2017 / 20:49

3 answers

4

Gonçalo, based on Gonçalo's answer , but I simplified the loop:

$postos = array();
while($array1 = mysqli_fetch_array($procura1)) $postos[] = $array1['posto'];

This works because when you do variavel[] = 'valor'; the value is added to the end of the array .

Depending on the intended structure, you have an even simpler alternative:

$tudo = mysqli_fetch_all($procura1);

This takes all the results at once, without having to do a loop manually. But in this case, you will get an array of arrays and not values.

If you are running PHP 5.5 or higher, you can use fetch_all like this:

$tudo   = mysqli_fetch_all($procura1, MYSQLI_ASSOC);   // Pegamos todas as linhas
$postos = array_column($tudo, 'posto');                // extraimos só a coluna 'posto'

The MYSQLI_ASSOC is for the columns to be indexed with names instead of numbers. If we use MYSQLI_NUM it would be necessary array_column($tudo, numero_da_coluna) , which complicates maintenance somewhat if something is changed in SELECT .

More details in the manual:

  

link

  

link

    
22.01.2017 / 21:39
1

For this you can make use of repetition loops from php.

  

Example with While

while($vetor = mysqli_fetch_array($procura1)){
   echo $vetor["posto"] . '<br/>';
}
  

Example with For

$dados = mysqli_fetch_array($procura1)
for($i = 0; $i < count($dados); $i++){
   echo $dados[$i]["posto"] . '<br/>';
}
  

Example with Foreach

$dados = mysqli_fetch_array($procura1)
foreach($dados as $dado){
   echo $dado["posto"] . '<br/>';
}
    
22.01.2017 / 21:17
-1

Gonçalo, you can do the following:

$contador = 0;
while($array1 = mysqli_fetch_array($procura1)){

$postos[$contador] = $array1["posto"];

$contador++;
}
    
22.01.2017 / 21:07