deepak bhardwaj February 2016

how to convert json string to array in php?

I have a json format and want to convert this to my customized format. Please help me for this conversion using PHP. Please help me out, how can i construct the above mentioned JSON array format. Here is my format:

 [{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]

And want result in this format:

[["Food & Drinks", 2],["Lifestyle", 1]]

Answers


Mister M February 2016

$array = json_decode($json, true);
$result = array();
for($i=0; $i<sizeof($array); $i++){
    $result[] = array_values($array[$i]);
}

$result will be your expected result


Chetan Ameta February 2016

try below solution:

$json = '[{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]';

$json_array = json_decode($json, true);

$new_array = array();

foreach($json_array as $arr){
    $new_array[] = array_values($arr);
}

print_r($new_array);

echo json_encode($new_array);

Output:

Array
(
    [0] => Array
        (
            [0] => Food & Drinks
            [1] => 2
        )

    [1] => Array
        (
            [0] => Lifestyle
            [1] => 1
        )

)
[["Food & Drinks","2"],["Lifestyle","1"]]

for more detail have alook at PHP: json_decode


Rajdeep Paul February 2016

The solution is:

So your code should be like this:

// suppose $json is your json string
$arr = json_decode($json, true);
$newArr = array_map('array_values', $arr);

// display $newArr array
var_dump($newArr);

Here $newArr is your desired array.


danjam February 2016

Version that casts 'data' value to int

$json = '[{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]';

$output = json_encode(array_map(function($v) {
    $v['data'] = (int) $v['data'];
    return array_values($v);
}, json_decode($json, true)));

// ["Food & Drinks",2],["Lifestyle",1]]
echo $output;

If int isn't needed

$output = json_encode(array_map('array_values', json_decode($json, true)));

Post Status

Asked in February 2016
Viewed 3,270 times
Voted 13
Answered 4 times

Search




Leave an answer