1

Assuming i have a JSON array like this example below :

[{"type":"food","alias":"meal"}]

And i want to assign this whole array to a particular key called "Dish" for example.

How can i archive this ?

Expected output should be something like :

"Dish":[{"type":"food","alias":"meal"}] 

I know how to create new key value pairs but never thought of assigning a key until now.

3 Answers 3

3
$json = '[{"type":"food","alias":"meal"}]';
$data = json_decode($json, true);
$data = array('Dish' => $data);
echo json_encode($data);
Sign up to request clarification or add additional context in comments.

Comments

1

You could do like this..

<?php
$json = '[{"type":"food","alias":"meal"}]';
$arr = array('dish'=>json_decode($json,true));
echo json_encode($arr);

Demo

Comments

1
echo json_encode(array('Dish' => json_decode($json, true)));
//{"Dish":[{"type":"food","alias":"meal"}]}

Comments

Your Answer

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