dongmen1860 2014-04-26 20:44
浏览 47
已采纳

array_combine有4个不同的数组到JSON

So I have 4 different arrays that I want to combine, because I need to encode them in JSON. I need the json_encode() output to resemble this:

[
    {

        id: 1
        user: "asd1",
        content: "Content 1",
        date: "3/12/2014 11:13 PM",

    }

]

However, I need to use a foreach loop because there are multiple entries like this. Here's an example of my arrays.

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )

    [user] => Array
        (
            [0] => asd1
            [1] => asd2
            [2] => asd3
            [3] => asd4
            [4] => asd5
        )

    [content] => Array
        (
            [0] => Content 1
            [1] => Content 2
            [2] => Content 3
            [3] => Content 4
            [4] => Content 5
        )

    [date] => Array
        (
            [0] => 3/12/2014 11:13 PM
            [1] => 1/13/2014 11:06 PM
            [2] => 1/13/2014 3:36 PM
            [3] => 11/24/2013 3:28 PM
            [4] => 11/10/2013 1:22 AM
        )

)

I've played around with foreach loops and array_combine, but with no success. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doukucai0099 2014-04-26 20:52
    关注

    array_map is the solution to your problem.

    $source = [
        'id' => [1, 2, 3],
        'user' => ['first user', 'second user', 'third user'],
    ];
    
    $result = array_map(function ($id, $user) {
        return compact('id', 'user');
    }, $source['id'], $source['user']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序