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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?