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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号