douyan4900
2015-06-01 09:52
浏览 52

将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
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题