dongzhui2636 2016-05-24 11:20
浏览 52
已采纳

生成PHP数组以模仿JSON格式

im a bit rusty with PHP and need some advice/help.

I am trying to generate a rough and quick api that returns some JSON data to populate a JavaScript chart. I am using PHP to query the Database. I can retrieve the stats per month/year, however I am struggling on a way to generate the PHP array prior to using JSON_ENCODE().

The format I am trying to get is:

                   {
                    y: 'January',
                    a: 150,
                    b: 90,
                    c: 50
                }, {
                    y: 'February',
                    a: 75,
                    b: 65,
                    c: 50
                }, {
                    y: 'March',
                    a: 50,
                    b: 40,
                    c: 50
                }, {
                    y: 'April',
                    a: 75,
                    b: 65,
                    c: 50
                }

and so on..through to December. a = 2014 / b = 2015 / c = 2016.

I have a DB query which takes a $year and $month parameter and it returns a count of records.

My initial thought was to use three arrays:

$months = array("January","February","March","April","May","June","July","August","September","October","November","December");
$years = array("2014","2015","2016");
$yearlabels = array("a","b","c");

However I cant see how I can do this to return an array in the format I want.

Any ideas?

  • 写回答

1条回答 默认 最新

  • dtxb75622 2016-05-24 11:29
    关注

    You can try

    $out = [];
    
    foreach($months as $month) {
       $arr = array();
       $arr['y'] = $month;
       foreach($yearlabels as $label) {
          $arr[$label] = '2';
       }
       $out[] = $arr;
    }
    
    echo json_encode($out);
    

    I hope this will help you. If not then let me know.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B