简体   繁体   English

Laravel:按键映射并在json中获得结果

[英]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. 我正在使用mailgun API和批量发送,为了正确发送带有recipent变量的批处理邮件,我必须提供一个有效的JSON编码字典,其中key是普通的收件人地址,value是带变量的字典。

The JSON object I wanna obtain is as follows: 我想获得的JSON对象如下:

'{ "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? 我怎么能这样做,是否可以使用laravel收集方法?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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