简体   繁体   中英

How to generate an array in PHP and JSON encode?

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}

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

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"}]

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"}]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM