-1

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]]
5
  • 1
    json_decode($json, true) Commented Feb 8, 2016 at 12:02
  • @SearchAndResQ typo.. :) Commented Feb 8, 2016 at 12:04
  • 1
    I know json decode. I want to customize this format to other format. Commented Feb 8, 2016 at 12:07
  • You just want to ignore the keys. I guess you want to use in some javascript. Commented Feb 8, 2016 at 12:09
  • Please provide some code where you can show what you have done until now. Commented Feb 8, 2016 at 13:02

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
$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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.