简体   繁体   中英

Laravel: Map by key and get result in json

I'm using mailgun API and batch sending , in order to properly send batch mails with recipent variables I must provide a valid JSON-encoded dictionary, where key is a plain recipient address and value is a dictionary with variables.

The JSON object I wanna obtain is as follows:

'{ "bob@example.com": {"username":"Bob", "id":1} ,
 { "pete@example.com": {"first":"Pete", "id":2} ,'

This is what I have so far (pseudocode):

$subs = Sub::all();

        foreach($subs as $sub)
        {
            $username = mailName($email->email);
            $id = $sub->id;
        }

How could I do this, is it possible to do with laravel collection methods?

Thanks in advance and sorry for noob question.

Yes, you can use collection to get the result, so back to your pseudocode, you can achieve it as this:

$data = collect();

foreach($subs as $sub)
{
    $data[$email->email] = [
      'username' => mailName($email->email),
      'id' => $sub->id
    ];
}

$data->toJson(); // this line will give you the expected result

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