Add JSON keys/values while creating another JSON PHP - php

I am trying to pass some JSON keys/values that I have to another JSON I am creating dynamically.
For example, this is the JSON I have in $json_create
{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4"
}
That comes over file_get_contents
$requestBody = file_get_contents('php://input');
$json_create= json_decode($requestBody);
And this is the JSON I am creating
$final_json = [
$json_create,
"type" => "message",
"elements" => $json_merge,
"actions" => $actions_json
];
echo json_encode($final_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Which print something like
{
"type": "message",
"elements": [
{
"msg_text": "This is a simple response message"
}
]
}
What I am trying to achieve is
{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4",
"type": "message",
"elements": [
{
"msg_text": "This is a simple response message"
}
]
}
There is quite a lot on that subject but somehow I could not succeed in implementing it.

Use array_merge rather than putting the $json_create inside the array.
$final_json = array_merge($json_create,
[
"type" => "message",
"elements" => $json_merge,
"actions" => $actions_json
]);

<?php
$json_create = '{"Key1": "Value 1", "Key2": "Value 2", "Key3": "Value 3", "Key4": "Value 4"}';
$json_create = (array) json_decode($json_create);
$your_array = [
"type" => "message",
"elements" => 'foo',
"actions" => 'bar'
];
$final_json = array_merge($json_create, $your_array);
$result = json_encode($final_json);
echo $result;
output
{
Key1: "Value 1",
Key2: "Value 2",
Key3: "Value 3",
Key4: "Value 4",
type: "message",
elements: "foo",
actions: "bar"
}

This can be done using union operator also.
$requestBody = '{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4"
}';
$json_create= json_decode($requestBody, true );
$other_array = [
"type" => "message",
"elements" => [],
"actions" => []
];
$final_json = $json_create + $other_array;

Related

Insert value in array after every index using php

I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);

MySQL to JSON PHP structure [duplicate]

How to Create Json Like This In Php?
[
[
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
],
[
"16226038",
"140",
"Courage The Cowardly Dog (1999-2002)",
"finished"
],
[
"16226020",
"101",
"[R.G. Mechanics] Call of Duty 4 Modern Warfare",
"finished"
]
]
I search a lot on the internet but couldn't get any result.
$arr = [
[
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
],
[
"16226038",
"140",
"Courage The Cowardly Dog (1999-2002)",
"finished"
],
[
"16226020",
"101",
"[R.G. Mechanics] Call of Duty 4 Modern Warfare",
"finished"
]
]
echo json_encode($arr);
Follow below link :
http://php.net/manual/en/function.json-encode.php
Just create an array
<?php
$arr = array(
array(
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
),
# ....
);
and for output as json
<?php echo json_encode($arr);?>
Here is an example of JSON encoding using the inbuilt json_encode PHP function which can create JSON formatted data from PHP array:
<?php
$arr = array(
'key 1' => "value 1",
'key 2' => "value 2",
'key 3' => "value 3"
);
echo json_encode($arr);
?>
Source: How to create JSON formatted text in PHP

how to Create Json in Php

How to Create Json Like This In Php?
[
[
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
],
[
"16226038",
"140",
"Courage The Cowardly Dog (1999-2002)",
"finished"
],
[
"16226020",
"101",
"[R.G. Mechanics] Call of Duty 4 Modern Warfare",
"finished"
]
]
I search a lot on the internet but couldn't get any result.
$arr = [
[
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
],
[
"16226038",
"140",
"Courage The Cowardly Dog (1999-2002)",
"finished"
],
[
"16226020",
"101",
"[R.G. Mechanics] Call of Duty 4 Modern Warfare",
"finished"
]
]
echo json_encode($arr);
Follow below link :
http://php.net/manual/en/function.json-encode.php
Just create an array
<?php
$arr = array(
array(
"16226281",
"11",
"Disclosure.1994.720p.BluRay.H264.AAC-RARBG",
"finished"
),
# ....
);
and for output as json
<?php echo json_encode($arr);?>
Here is an example of JSON encoding using the inbuilt json_encode PHP function which can create JSON formatted data from PHP array:
<?php
$arr = array(
'key 1' => "value 1",
'key 2' => "value 2",
'key 3' => "value 3"
);
echo json_encode($arr);
?>
Source: How to create JSON formatted text in PHP

Replace double quotes in a json string using php

I need to convert a JSON string in array using PHP, but I need to escape double quotes.
$string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*],
["label":"Email","type":"email","placeholder":"mail#example.com","name":"email",*],
["label":"Message","type":"textarea","value":"In this box you can insert a link"]';
$jsonify = strip_tags($string,"<a>");
$jsonify = str_replace('*','"required":"required"',$jsonify);
$jsonify = str_replace('[','{',str_replace(']','}',$jsonify));
$jsonify = str_replace(array("\r\n", "\r"),"",$jsonify);
$jsonify = preg_replace("/\s+/", " ", $jsonify);
$jsonify = '['.jsonify.']';
echo $jsonify;
// OUTPUT IS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
// BUT IS NOT JSON VALID. IT SHOULD BE THIS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
How can I obtain a valid JSON string?
your string is not a json valid
this is a $string json valid
[
{
"label": "Name",
"type": "text",
"placeholder": "Mario",
"name": "name"
},
{
"label": "Email",
"type": "email",
"placeholder": "mail#example.com",
"name": "email"
},
{
"label": "Message",
"type": "textarea",
"value": "In this box you can insert a <a href='#' target='_blank'>link</a>"
}
]
test this,and remove other code strip_tags,Str_replace,preg_replace
echo json_encode($string);
You get a valid json file by simply passing your array/string to json_encode like this :
$array = array(
array("label" => "Name", "type" => "text", "placeholder" => "Mario", "name" => "name"),
array("label" => "Email", "type" => "email", "placeholder" => "mail#example.com", "name" => "email"),
array("label" => "Message", "type" => "textarea", "value" => "In this box you can insert a <a href='#' target='_blank'>link</a>")
);
$json = json_encode($array);
var_dump($json);

How can I put certain rows from CSV file into JSON arrays within a JSON object? (PHP)

I am taking CSV data and using PHP to generate JSON, but I'd like to know if it's possible to take certain rows from the CSV to create arrays within an object, see goal below for clarity:
I have the following example CSV data:
songId, title, artists:name[1], artists:main[1], artists:name[2], artists:main[2]
"trk-01", "Track 1", "artist 1", "true", "artist 2", "false"
"trk-02", "Track 2", "artist 3", "true", "artist 4", "false"
(This can be formatted to suit the solution)
The following PHP is being used to create JSON from the above CSV:
if (($handle = fopen('example.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
$completeobj = array("tracks" => $complete);
$result = array_merge($completeobj);
fclose($handle);
echo json_encode($result, JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($result, JSON_PRETTY_PRINT));
fclose($fp);
This is generating JSON that looks like:
{
"tracks": [
{
"songId": "trk-01",
"title": "Track 1",
"artists:name[1]": "artist 1",
"artists:main[1]": "true",
"artists:name[2]": "artist 2",
"artists:main[2]": "false"
},
{
"songId": "trk-02",
"title": "Track 2",
"artists:name[1]": "artist 3",
"artists:main[1]": "true",
"artists:name[2]": "artist 4",
"artists:main[2]": "false"
}
]
}
But my goal is to take those 'artists' rows in the CSV and put their values into an array within the object artists, see desired json below:
{
"tracks": [
{
"songId": "trk-01",
"title": "track 1",
"artists":
[
{
"name": "Artist 1",
"main": true
},
{
"name": "Artist 2",
"main": false
}
]
},
{
"songId": "trk-02",
"title": "track 2",
"artists":
[
{
"name": "Artist 3",
"main": true
},
{
"name": "Artist 4",
"main": false
}
]
}
]
}
If anyone could suggest a method of achieving this or show me an example that may help me to figure it out that would be ace!
try this before your json_encode
$new_result = array();
foreach($result['tracks'] as $trackdata){
$id = $trackdata['songId'];
$title = $trackdata['title'];
$name1 = $trackdata['artists:name[1]'];
$name2 = $trackdata['artists:name[2]'];
$main1 = $trackdata['artists:main[1]'];
$main2 = $trackdata['artists:main[2]'];
$new_result['tracks'][]=array(
'songID' => $id,
'title' => $title,
'artists' => array(
0 => array(
'name' => $name1,
'main' => $main1,
),
1 => array(
'name' => $name2,
'main' => $main2,
),
),
);
}

Categories