PHP: Converting string into json array [duplicate] - php

This question already has answers here:
PHP: Give a name to an array of JSON objects?
(5 answers)
Closed 3 years ago.
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?

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}}]}

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

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.

Related

PHP using array_unique and then converting to JSON, without the indexes [duplicate]

This question already has answers here:
json_encode PHP array as JSON array not JSON object
(4 answers)
How to get values only array in php?
(5 answers)
Closed last year.
I am querying my DB, looping through the results and then converting to JSON.
I am also using array_unique function.
The problem is my JSON file includes the indexes, how can I return in JSON format without the indexes?
I need it this way as I am then planning to feed the JSON array directly into an apexcharts.js chart.
Here is my code:
$month = [];
$value = [];
foreach($rows as $row) {
$month[] = $row['Source'];
$value[] = $row['Days_To_Report'];
}
$month1 = array_unique($month);
$month_json = json_encode($month1, JSON_PRETTY_PRINT);
$fp = fopen('value.json', 'w');
fwrite($fp, $month_json);
fclose($fp);
And here is the JSON output:
{
"0": "CGI Insurance",
"4": "THIRD PARTY CAPTURE - CGI"
}
What I need is this:
{
"CGI Insurance",
"THIRD PARTY CAPTURE - CGI"
}
How can I do this?
Thanks

How to convert string to json, and get all key's value in PHP [duplicate]

This question already has answers here:
convert query String to json in php
(3 answers)
Closed 3 years ago.
I have some strings, the format like this
name=bob&age=10&sex=male&weight=80&...
And I want to convert it to json format
{
"name":"bob",
"age":"10",
"sex":"male",
"weight":"80",
//and more
}
I wrote some codes, but I don't know how to continue
$co="name=bob&age=10&sex=male&weight=80&...";
$toarray = explode("&", $co);
Does someone give some tips? Many thanks.
You can use parse_str for the same,
parse_str("name=bob&age=10&sex=male&weight=80", $output);
echo json_encode($output);
print_r($output); // if you need normal array.
Explanation: It will capture all URL string as an array to output. As I see you need JSON string I used json_encode to convert array to string.
Here is link you can refer for details.
Demo.
$co="name=bob&age=10&sex=male&weight=80&...";
$result = [];
foreach (explode('&', $co) as $item) {
list($key, $value) = explode('=', $item);
$result[$key] = $value;
}
echo json_encode($result);

PHP string array to php array [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have this string array:
["652","110","111","1032","118","416","147","121","112","1033","113","1031","868"]
I need to read each value so to get
652
110
111
1032
i try to convert string array using explode and then foreach but is not working...
$channels = explode('"', $string_array);
foreach($channels as &$channel) {
echo $channel.'<br>';
}
it's an JSON format, so use json_decode
$json = '["652","110","111","1032","118","416","147","121","112","1033","113","1031","868"]';
$array = json_decode($json, true);
foreach($array AS $channel) {
echo $channel.'<br>';
}

convert json Array to single Json Object

I was wonder whether it is possible to convert a json Array to a single json object in php?
I mean below json Array:
[{'x':'y','k':'l'}, {'q':'w', 'r':'t'}]
Can be converted to:
{'0':{'x':'y','k':'l'}, '1':{'q':'w', 'r':'t'}}
Use json_encode with the JSON_FORCE_OBJECT parameter
$json = "[{'x':'y','k':'l'}, {'q':'w', 'r':'t'}]";
$array = json_decode($json, true); // convert our JSON to a PHP array
$result = json_encode($array, JSON_FORCE_OBJECT); // convert back to JSON as an object
echo $result; // {"0":{"x":"y","k":"l"},"1":{"q":"w","r":"t"}}
JSON_FORCE_OBJECT
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Please try below code.
$array[] = array('x' => 'y','k' => '1');
$array[] = array('q' => 'w','r' => 't');
echo json_encode($array,JSON_FORCE_OBJECT);

Converting multiple strings into JSON arrays

I have multiple strings that looks like the following: 11-16, 16-12, 14-16
I will have multiple of these, and I need to store them in JSON. I need to store it in the following format:
[
{
"score_1": 11,
"score_2": 16
},
{
"score_1": 16,
"score_2": 12
},
{
"score_1": 14,
"score_2": 16
}
]
with score_1 being the first number, and score_2 being the second number. How will I be able to do this in PHP?
Thanks
First create an array. Next create an object, then explode the string on the hyphen and store the intval'd first and second number in the object. Push that object into your array. Repeat for as many strings as you have. Finally, use json_encode to get a JSON-encoded string.
$arr = [];
function addString($str, &$arr) {
$str = explode("-", $str);
$obj = new stdClass();
$obj->score_1 = intval($str[0]);
$obj->score_2 = intval($str[1]);
$arr[] = $obj;
}
addString("11-16", $arr);
addString("16-12", $arr);
echo json_encode($arr);
Output:
[{"score_1":11,"score_2":16},{"score_1":16,"score_2":12}]
Edit: Updated the above code to use intval as the OP has integers in his object in the expected output.
Two steps:
Convert the strings to the according data structure (e.g. array of stdClass objects).
Convert that data structure to JSON.
Note: Since you already know the output you want, you could parse that output to get an idea how its representation in PHP would look like, as a suggestion for the results of the first step.

Categories