dss087358 2019-04-28 20:13
浏览 57

Laravel:按键映射并在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.

  • 写回答

1条回答 默认 最新

  • dongmi4809 2019-04-28 20:24
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源