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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题