简体   繁体   中英

Create array of objects with foreach loop in php

How I am currently doing it

$arr = array(
    array(
        'date'=>$response2->Msg[0]->Date, 'sender'=>$response2->Msg[0]->Sender, 'message'=>$response2->Msg[0]->Message
    ),
    array(
        'date'=>$response2->Msg[1]->Date, 'sender'=>$response2->Msg[1]->Sender, 'message'=>$response2->Msg[1]->Message
    )
);
echo json_encode($arr);
var_dump($response2);

The above code creates an array of objects which is what I need. Example Output:

[{date":"06-Jan-20 04:00:00","sender":"dsdssf","message":"aaaaa},{date":"06-Jan-20 04:00:00","sender":"addfdfd","message":"ncccc2"]

I want to do the same thing with a loop to avoid repetition.

What I have tried

foreach ($response2->Msg as $key => $value) {
    $arr= array(
        'date'=>$value->Date, 'sender'=>$value->Sender, 'message'=>$value->Message
    );
}

The above code gives this output it stores the last object only

{"date":"06-Jan-20 04:00:00","sender":"addfdfd","message":"ncccc2"}

Try

$arr = array();
foreach ($response2->Msg as $key => $value) {
    $rec = array('date'=>$value->Date, 'sender'=>$value->Sender, 'message'=>$value->Message);
    array_push($arr, $rec);
}

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