Home > Mobile >  How to echo PHP array in a format
How to echo PHP array in a format

Time:04-01

Is there a way I can echo an array of value in this format[200,135,667,333,526,996,564,123,890,464,655] I have my PHP code as below:


 $sql_sum_up = "SELECT * FROM `payment`";
      $result_sum_up = mysqli_query($conn,$sql_sum_up);
      $count_sum_up = mysqli_num_rows($result_sum_up); 
      
      while($row_sum_up = mysqli_fetch_array($result_sum_up,MYSQLI_ASSOC)){

      $price = $row_sum_up['price'];
}

I want when I echo $price it should come in this format [200,135,667,333,526,996,564,123,890,464,655]

CodePudding user response:

  • Start of by indenting your code correctly. There's almost always a function for auto-formatting in most editors, such as Visual Studio Code, NetBeans, etc. Or use an online tool to do it.
  • Correct your SQL query since there's no point getting all values if you just read the price value and you are ordering without mentionning the field name:
    SELECT `price` FROM `payment` ORDER BY `field_name` DESC
    
  • Create an array variable which you will fill with the prices:
    $prices = [];
    
  • In your loop reading the database values, fill the array:
    $prices[] = $row_sum_up['price'];
    
    Alternatively, you could also fetch all values instead of looping. By the way, it's best to use PHP's PDO abstraction layer instead of mysqli_() functions.
  • After the loop, export it to JSON:
    print json_encode($prices);
    

CodePudding user response:

first of all, as someone already mentioned in the comments you have an error in your SQL synthax. The correct ORDER BY synthax is "ORDER BY [field-name] DESC"

You could achieve what you want in different ways.

First of all you want to create an array that contains all prices:

$sql_sum_up = "SELECT * FROM `payment`";
$result_sum_up = mysqli_query($conn,$sql_sum_up);
$count_sum_up = mysqli_num_rows($result_sum_up); 
$prices = [];  //Create the prices array 
while($row_sum_up = mysqli_fetch_array($result_sum_up,MYSQLI_ASSOC)){
      $prices[] = $row_sum_up['price']; //This pushes every price into the array
}
  1. Make use of join/implode - PHP.net join function

    echo '['.join(',',$prices).']';

  2. You could use json_encode function PHP.net json_encode function

    echo json_encode($prices);

  •  Tags:  
  • php
  • Related