Peacefull Peacefull - 5 months ago 33
Ajax Question

Restructure multidimensional array in PHP to wanted JSON

I'm trying to restructure a multidimensional array but i can't manage it. I'm not very good with array's... So I would like to request your assistance please !

Here is my actual 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
)

)

)


Then i use
json_encode
to combine it with AJAX :

echo json_encode($jsonArray, JSON_UNESCAPED_UNICODE);


And the result is :

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


I'm trying to use FusionCharts example from here !

As you see i need to create structured arrays like this :

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

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


Then in my AJAX code i set this for the charts :

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


My final request is how i can make those arrays arrayNeedle1 & arrayNeedle2, please ?

Thank you in advance for your help and sorry for my poor skills in arrays !

Best regards.

Answer

As you have multidimensional nested arrays, restructuring it in place would be overcomplicated way, instead you may create a new array with needed structure using the following approach:

// 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);

The output:

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