-1

I need to convert this string

$json_string = [{"insert":"Test11"},{"insert":"","attributes":{"heading":3}}];

Into this json array

{
 "ops": 
   [{"insert":"Test11"},{"insert":"","attributes":{"heading":3}}]
}

I converted the original string into array like this

$array = json_decode($json_string);

Now how to create a json object named "ops" that contains this array to be parsed using delta parser https://github.com/nadar/quill-delta-parser?

1
  • $json_obj = new array(); $json_obj['ops'] = $array Commented Dec 4, 2019 at 21:34

3 Answers 3

2

You could decode it, wrap it in an array with a key "ops" and encode it again

$json_string = json_encode(["ops" => json_decode($json_string, true)]);
echo $json_string;

Output

{"ops":[{"insert":"Test11"},{"insert":"","attributes":{"heading":3}}]}
Sign up to request clarification or add additional context in comments.

Comments

1

You should make named index array and encode again like this:

   $json_string =' [{"insert":"Test11"},{"insert":"","attributes":{"heading":3}}]';
    $array = json_decode($json_string);
    $array['ops'] = $array;
    echo json_encode($array);

Comments

1

This works too using type casting as shorthand:

(object)['ops'=>'[{"insert":"Test11"},{"insert":"","attributes":{"heading":3}}]']

/* Output
object(stdClass)#1 (1) {
  ["ops"]=>
  string(50) "[{insert:Test11},{insert:,attributes:{heading:3}}]"
} */

It's efficient, easy to keep in mind, easy to read and this can save using intermediary variables.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.