duan0414 2012-07-19 10:16
浏览 408
已采纳

将多维php数组转换为JSON对象数组

I need to create a multi-dimensional array in php and want to use it in a jQuery script as a JSON array of objects;

The required output in the jQuery script should look like this:

data = [
        { Month:'April', Comms:1000, Fees:200, Gains: 200},
        { Month:'May',   Comms:1200, Fees:300, Gains: 300}
        ]   

Currently my php arrays are generated as follow:

    $data1[] = array(
        'Month' => 'April',
        'Comms' => 1000,
        'Fees'  => 200,
        'Gains' => 200      
    );      
    $data2[] = array(
        'Month' => 'May',
        'Comms' => 1200,
        'Fees'  => 300,
        'Gains' => 300      
    );

    echo json_encode($data);

My question is how to combine data1 and data2 into the data array in the json_encode php function which will produce the required jQuery JSON array of objects?

I do have the values of the different array fields and can create data1 and data2 in a different way, so the data is flexible and I can combine them in any other way which will produce the data array which will output them in the required JSON format.

Any help will be highly appreciated, I have seen question regarding this subject but none which address the issue I am facing.

  • 写回答

6条回答 默认 最新

  • douwu8060 2012-07-19 10:24
    关注

    You'll want to merge both Arrays into a new Array of Arrays. See the manual for more information.

    $data = array_merge($data1, $data2);
    echo json_encode($data)
    

    or, more simply by using the + operator:

    echo json_encode($data1 + $data2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分