How to receive an array and print its contents using PHP?

0

I need to know how to store the data of an array into a variable, using the looping below:

Receiving data:

$sql="SELECT 'devicetoken' FROM 'devicetokensios'  ORDER BY 'index'";

  $resultado = mysql_query($sql) or die ("Erro .:" . mysql_error());

$deviceToken = array();

  while($r = mysql_fetch_assoc($resultado))
{
    $deviceToken [] = $r;
}
mysql_close();

After receiving the data, how do I loop through and control the array data using its index:

Example of how to use array data:

for($index = 0; $index <= count($deviceToken); $index ++){

$outraVarial = $deviceToken[$index];

}
    
asked by anonymous 14.11.2014 / 16:54

2 answers

3

Disregarding the syntax error pointed out by Sergio and considering the requirement that the array be printed as a string, you have, without iterating, at least three options but all followed by an echo or print:

  • implode ()

    <?php echo implode( '', $deviceTokens );
    
  • The implode () problem is that it does not work with associative arrays so if the array has string indices, they will be ignored and the output will not be as expected.

  • serialize ()

    <?php echo serialize( $devideTokens );
    
  • The problem of serialize is the rigidity of the resulting information. Once you have serialized an array you can not do anything useful without de-serializing it. So it's a more suitable format for storing data that does not require normalization.

  • json_encode ()

    <?php echo json_encode( $deviceTokens );
    
  • The most flexible of the options because it can be universal because it can be manipulated even by other languages.

    And you have the option to iterate, if all else fails:

    $output = NULL;
    
    foreach( $deviceTokens as $key => $value ) {
    
        // É óbvio que você não vai fazer assim :p
    
        $output . 'Chave: ' . $key . "\nValor: " . $value;
    }
    
    echo $output;
    
        
    14.11.2014 / 17:07
    0

    Okay, I got what I wanted!

    Thank you.

    Below the code:

    $meuArray = array();
    
    $meuArray []= "A";
    $meuArray []= "k";
    $meuArray []= "Blan";
    
    
    for($lop = 0; $lop < count($meuArray);$lop++){
    
    echo ($meuArray[$lop]);
    
    
    }
    
        
    15.11.2014 / 01:59