-1

I have this JSON Object Array Type Data that I want to insert into array with keys. If I do print_r, the data seen as follows :

[{"comment":"hola hi ","datecreated":"2017-02-27 13:53:25"},{"comment":"hola hi harambeh ","datecreated" :"2017-02-27 13:53:30"}]

Here's my related code :

$data = json_decode($_REQUEST['array']);

$formdata = [];

foreach($data as $value){
    $formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);
}

However, the result array only took the last object, which are

Array
(
    [comment] => hola hi harambeh 
    [date_created] => 2017-02-27 13:53:30
)

Obviously I need every data, not just last one. This should be easy in JavaScript.

Any ideas and helps much appreciated.

LuFFy
  • 8,799
  • 10
  • 41
  • 59
Rayan Suryadikara
  • 237
  • 1
  • 3
  • 17
  • 1
    use `$formdata[]` in foreach loop & there is no need to insert in new array because if you use `json_decode($_REQUEST['array'],true)` gives array read [manual](http://php.net/manual/en/function.json-decode.php) – gaurav Feb 27 '17 at 07:10
  • 1
    You should read the [manual](http://php.net/manual/en/function.json-decode.php) about `json_decode()`. Simply pass `true` as a second argument and it will be decoded as arrays instead of objects. No need to do it manually. – M. Eriksson Feb 27 '17 at 07:11

3 Answers3

1

You are updating the whole array and what you need is to add an item to the array so you will need []. Change

     $formdata = array('..........

to

     $formdata[] = array('......
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
0

Try below

You need change $formdata To $formdata[ ]

Replace

foreach($data as $value){
        $formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);
    }

With

foreach($data as $value){
        $formdata[] = array('comment' => $value->comment, 'date_created' => $value->datecreated);
    }
Shailesh Chauhan
  • 673
  • 5
  • 20
0

Change this

foreach($data as $value){
$formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);}

to this

foreach($data as $value){
$formdata[] = array('comment' => $value->comment, 'date_created' => $value->datecreated);}

Problem was on assigning a new array in every iteration to same variable rather than adding a new item to existing array

Rakesh Mishra
  • 358
  • 5
  • 17