-1

I want to create a JSON format of an array using PHP, but my result is only the latest data and is being replaced.

How can I show all days?

Code:

for($i=1;$i<5;$i++) { 
  $ar -> date = date("j F y",strtotime("+".$i." days"));
  $ar -> id = $i;
}

echo json_encode($ar);

Current result:

{"date":"8 May 19","id":4}
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 2
    You may also find [I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?](https://stackoverflow.com/questions/3207749/i-have-2-dates-in-php-how-can-i-run-a-foreach-loop-to-go-through-all-of-those-d) useful. – Nigel Ren May 04 '19 at 05:48

3 Answers3

2

You need to create an array to store the values into so that you don't overwrite them on each pass through the loop:

$ar = array();
for($i=1;$i<5;$i++) { 
  $ar[] = array('date' => date("j F y",strtotime("+".$i." days")), 'id' => $i);
}
echo json_encode($ar);

Output:

[
 {"date":"5 May 19","id":1},
 {"date":"6 May 19","id":2},
 {"date":"7 May 19","id":3},
 {"date":"8 May 19","id":4}
]

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
1

You can use array_push to do that also:

$ar = array();
for ($i = 1; $i < 5; $i++) {
    array_push($ar, ["id" => $i, "date" => date("j F y", strtotime("+" . $i . " days"))]);
}

$ar = json_encode($ar);
var_dump($ar);

Output

string(109) "[{"id":1,"date":"5 May 19"},{"id":2,"date":"6 May 19"},{"id":3,"date":"7 May 19"},{"id":4,"date":"8 May 19"}]"

Emma
  • 27,428
  • 11
  • 44
  • 69
1

You can create array with custom field name

      <?php

      $AR = array();
      for($i=1;$i<5;$i++) {
        $a=array();
        $a['id']=$i;
        $a['date'] = date("j F y",strtotime("+".$i." days"));
        $AR[]=$a;
      }
      echo json_encode($AR); ?>

output :

      [{"id":1,"date":"5 May 19"},{"id":2,"date":"6 May 19"},{"id":3,"date":"7 May 19"},{"id":4,"date":"8 May 19"}]
Ghanshyam Nakiya
  • 1,602
  • 17
  • 24