2012-07-19 10:16
浏览 391


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.

图片转代码服务由CSDN问答提供 功能建议

我需要在php中创建一个多维数组,并希望在jQuery脚本中将其用作JSON数组 对象;


  data = [
 {Month:'April  ',Comms:1000,费用:200,收益:200},
   \  n 


  $ data1 [] = array(
  'Comms'=> 1000,
'费用'=> 200,
'Gains'=> 200 
 $ data2 [] = array(
'Comms'=> 1200,
'费用'=> 300,
'收益'=> 300  
 echo json_encode($ data); 

我的问题是如何将data1和data2组合到json_encode php函数中的数据数组中 这将产生所需的jQuery JSON对象数组?

我确实拥有不同数组字段的值,并且可以以不同的方式创建data1和data2,因此数据非常灵活,我可以将它们以任何其他方式组合在一起,从而产生 数据数组将以所需的JSON格式输出它们。


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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)
    解决 无用
    打赏 举报

相关推荐 更多相似问题