在PHP中重构多维数组以获得JSON

时间:2016-06-22 12:39:15

标签: php arrays json ajax multidimensional-array

我正在尝试重组多维数组但我无法管理它。我对阵列的表现不太好......所以我想请求你的帮助!

这是我的实际数组:

$jsonArray = Array
(
[0] => Array
    (
        [category] => Array
            (
                [label] => avr 2016
            )

        [data] => Array
            (
                [value] => 39
            )

    )

[1] => Array
    (
        [category] => Array
            (
                [label] => mai 2016
            )

        [data] => Array
            (
                [value] => 335
            )

    )

[2] => Array
    (
        [category] => Array
            (
                [label] => jun 2016
            )

        [data] => Array
            (
                [value] => 206
            )

    )

)

然后我用json_encode将它与AJAX结合起来:

echo json_encode($jsonArray, JSON_UNESCAPED_UNICODE);

结果是:

[{"category":{"label":"avr 2016"},"data":{"value":"39"}},{"category":{"label":"mai 2016"},"data":{"value":"335"}},{"category":{"label":"jun 2016"},"data":{"value":"206"}}]

我正在尝试使用here中的FusionCharts示例!

如您所见,我需要创建这样的结构化数组:

"category": [
                    { "label": "Jan 2012" },
                    { "label": "Feb 2012" },
                    { "label": "Mar 2012" },
                    { "label": "Apr 2012" },

"data": [
                    { "value": "27400" },
                    { "value": "29800" },
                    { "value": "25800" },
                    { "value": "26800" },

然后在我的AJAX代码中,我为图表设置了这个:

var apiChart = new FusionCharts({
                type: 'scrollline2d',
                renderAt: 'chart-totalAnnee',
                width: '550',
                height: '350',
                dataFormat: 'json',
                dataSource: {
                    "chart": chartProperties,
                    "categories": arrayNeedle1,
                    "dataset": arrayNeedle2
                }
            });

我最后的要求是如何制作那些数组arrayNeedle1& arrayNeedle2,拜托?

提前感谢您的帮助,对于我在阵列中的糟糕技能感到抱歉!

最好的问候。

1 个答案:

答案 0 :(得分:1)

由于您拥有多维嵌套数组,因此重组它将会过于复杂,而您可以使用以下方法创建具有所需结构的新数组:

// supposing $arr is your initial array
$new_arr = ["category" => [], "data" => []];  // base structure
foreach ($arr as $item) {
    $new_arr["category"][] = ["label" => $item["category"]["label"]];
    $new_arr["data"][] = ["value" => $item["data"]["value"]];
}

echo json_encode($new_arr, JSON_PRETTY_PRINT);

输出:

{
    "category": [
        {
            "label": "avr 2016"
        },
        {
            "label": "mai 2016"
        },
        {
            "label": "jun 2016"
        }
    ],
    "data": [
        {
            "value": "39"
        },
        {
            "value": "335"
        },
        {
            "value": "206"
        }
    ]
}