douyan4900 2015-06-01 09:52
浏览 55
已采纳

将2D PHP数组转换为2D Json对象以在图形上绘图

I'm working on this part of code since weeks now and I'm really unable to solve my issue. I'll try to explain my code deeply.

I'm fetching values from my MySQL database. Using the code below I'm able to create a 2D PHP array:

        for ($i=2, $k=2; $i<11, $k<11; $i++, $k++) {
            $roe_array[] = array( $date_y[$i] => $roe[$k]);
        }

The output of this code is the following

Array
(
    [0] => Array
        (
            [2006] => 13.83
        )

    [1] => Array
        (
            [2007] => 16.43
        )

    [2] => Array
        (
            [2008] => 14.89
        )

    [3] => Array
        (
            [2009] => 18.92
        )

    [4] => Array
        (
            [2010] => 22.84
        )

    [5] => Array
        (
            [2011] => 27.06
        )

    [6] => Array
        (
            [2012] => 28.54
        )

    [7] => Array
        (
            [2013] => 19.34
        )

    [8] => Array
        (
            [2014] => 18.01
        )

)

So, I convert the 2D PHP array in Json

$roe_enc = json_encode( $roe_array );

The output is:

[{"2006":"13.83"},{"2007":"16.43"},{"2008":"14.89"},{"2009":"18.92"},{"2010":"22.84"},{"2011":"27.06"},{"2012":"28.54"},{"2013":"19.34"},{"2014":"18.01"}]

Considering I have to plot it in a javascript script, I want an object like the following:

[[2006, 13.83],[2007, 16.43],[2008, 14.89],[2009, 18.92], [2010, 22.84],[2011, 27.06],[2012, 28.54],[2013, 19.34],[2014, 18.01]]

Can you help me to solve this issue? Thanks for your support.

  • 写回答

1条回答 默认 最新

  • duanbeng1923 2015-06-01 09:56
    关注

    Now the year is a key and you want it to be a value in an array so you would have to generate an array that contains 0-based indexed arrays instead of key-value pairs. The reason is that any other index than a sequential 0-based ones get converted to a key-value pairs in json as javascript only knows 0-based arrays.

    To do that you should change your loop to:

    for ($i=2, $k=2; $i<11, $k<11; $i++, $k++) {
        // add an array with 2 values instead of a key-value pair
        $roe_array[] = array( $date_y[$i], $roe[$k] );
        //                               ^ add 2 elements instead of 1
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库