I have this JSON string.
[
{
"name": "user_title",
"value": "Bapak."
},
{
"name": "user_firstname",
"value": "Test"
},
{
"name": "user_lastname",
"value": "XXX"
}
]
This string generated dynamically. It may has more or less. I use JSON Decode to process it in PHP.
$json_form = json_decode($json_string,true);
$user_title = $json_form[0]['value'];
$user_firstname = $json_form[1]['value'];
$user_lastname = $json_form[2]['value'];
How do I check the variable user_title even exist in the string?
If it exist I should get the value but if not that means $user_title = NULL.
You might want to consider mapping your JSON into a key/value array using array_column; then it is easy to check for the existence of a value. For example:
$json_form = json_decode($json_string, true);
$values = array_column($json_form, 'value', 'name');
$user_title = $values['user_title'];
$user_firstname = $values['user_firstname'];
$user_lastname = $values['user_lastname'];
echo "title: $user_title\nfirst name: $user_firstname\nlast name: $user_lastname\n";
Output for your sample data is:
title: Bapak.
first name: Test
last name: XXX
It's also easy to add default values when a key is missing, for example:
$user_title = $values['user_title'] ?? '';
Related
This is my json.json file content
{
"Title": "Hello World",
"Inputs": [
{
"Id": "1",
"Title": "One"
},
{
"Id": "15",
"Title": "Fifteen"
}
]
}
I am trying to modify it as the follows -
$text = file_get_contents("json.json");
$json = json_decode($text,true);
foreach($json["Inputs"] as $input){
if($input["Id"]== "15"){
$input["Title"] = "This is from me.";
}
}
$new = json_encode($json);
file_put_contents('json.json', $new);
But the file is not being updated.
Any idea?
Your JSON in the example is improperly formatted, but the issue you are having is that you do not set the title in the original array. You change the copy that is passed to the foreach loop.
Change your foreach loop to this and your changes should be shown:
foreach($json["Inputs"] as $key => $input){
if($input["Id"]== "15"){
$json["Inputs"][$key]["Title"] = "This is from me.";
}
}
The foreach loop takes the value by reference, so changing the $json['Inputs'] will change the original value, whereas changing $input modifies the copy that is passed to the loop, and does not change the original json data. There are ways to pass by reference to the foreach loop, but this seems like a simpler solution.
I have 2 different jsons and I need to get one inside the other.
JSON 1
[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]
JSON 2
{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}
I need the second one inside the first one for use with javascript
I tried the array_merge() php function without getting results
since JSON1 is an array of JSON-object and JSON2 is just a JSON-object.
in addition to that you said, 'I need the second one inside the first one for use with javascript'. therefore, you can test this code https://3v4l.org/1HGNF/perf#output
please compare all performances in mem-usage and timing
$j1 = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$j2 = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j1 = json_decode($j1, true);
$j2 = json_decode($j2, true);
$j1[] = $j2;
var_dump(json_encode($j1));
You can use json_decode with parameter true to convert JSON into an array , then use array_merge to make them a single array
$j1 = '[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]';
$j1arr = json_decode($j1, true);
$j2 = ' {
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j2arr = json_decode($j2, true);
$r = array_merge($j1arr[0], $j2arr);
You can use the merged array in javascript by using json_encode
json_encode($r)
https://3v4l.org/WKX1U
Do it simply like this way without any extra array merging methods-
<?php
$json1 = json_decode('[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]',1);
$json2 = json_decode('{"Texto":" VENDO O PERMUTO","imageJob":{"pathConvertido":"ClasificadosPNG/0011311247.png","convertido":true,"id":5011},"rubroClasificado":{"CodigoRubro":150,"id":76}}',1);
$json1[] = $json2; // add second json to first json
print_r($json1);
echo json_encode($json1);
?>
WORKING DEMO: https://3v4l.org/qhsJq
As you said you want to process the resulting data in JavaScript, and as per your question you want second json inside the first json. You can do something like this.
You will get a json as final result.
$first = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$first = str_replace(['[',']','}'], '', $first);
$second = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$second = preg_replace('/\{/', ',', $second,1);
print_r($first.$second);
As result you will get a valid json, second json inside your first json, you can validate here
I have a .json file and I want to append an object to a vector in the file, but I got some errors.
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.
Here is an example of my .json file:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.
What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!
Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.
Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.
So
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
can become simply
array_push($jsonarray['packages'], $myObj);
P.S. You can also remove the warning about "Creating default object from empty value" by writing
$myObj = new \stdClass();
just before the line
$myObj->short = $_POST["short"];
so that you're adding your properties to an object which already exists.
This question already has answers here:
Create JSON object using PHP [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to create JSON in a PHP variable that represents the following JSON structure:
{
"nodes": [
{"id": "example#email.com", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "example#email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.
The code I currently have is:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example#email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
However when I view the output in JSON format there are some issues:
{
"nodes": ["\"id\": \"example#email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"example#email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.
It is better using json_encode, note that you should use arrays all the way:
$entityarray['nodes'][] = array( 'id' => 'example#email.com'
, 'group' => 1
);
Try this
$result = array();
$nodes_array = array();
$temp = array();
$temp["id"] = "example#gmamil.com";
$temp["group"] = 1;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["group"] = 2;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 9057673495b451897d14f4b55836d35e";
$temp["group"] = 2;
$nodes_array[] = $temp;
$links_array = array();
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["value"] =1;
$links_array[] = $temp;
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 9057673495b451897d14f4b55836d35e";
$temp["value"] =1;
$links_array[] = $temp;
$result["nodes"] = $nodes_array;
$result["links"] = $links_array;
echo json_encode($result);
I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).
I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:
author1 name, author2 name, article title, publication title, key
This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.
The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.
[
{
"key": "123456",
"state": 100,
"data": {
"articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
"authors": [
{
"firstName": "Sam C.",
"lastName": "Smith"
},
{
"firstName": "Maxine P.",
"lastName": "Jones"
}
],
"pubTitle": "Australian Journal of Zoology",
"tags": [
{
"tag": "scary"
},
{
"tag": "secret rulers of the world"
}
]
}
},
{
"key": "001122",
"state": 100,
"data": {
"articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
"authors": [
{
"firstName": "Marius",
"lastName": "Damstra"
}
],
"pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
"tags": [
{
"tag": "Wrong Wombat"
}
]
}
}
]
If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.
decode your json as array and iterate it as any array as flowing:
$json_decoded= json_decode($json,true);
$tab="\t";
foreach ($json_decoded as $key => $val) {
echo "Article ".$val["key"]."\n" ;
echo $tab."Authors :\n";
foreach ($val["data"]["authors"] as $key => $author){
echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
}
echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
echo $tab."Key: ".$val["key"]."\n";
}
run on codepad
and you can use the same method for xml as flowing:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same
for xml you can use the SimpleXml's functions
or DOMDocument class
Tip
to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging
Something like this might be a good start for you:
$output = [];
// Loop through each entry
foreach ($data as $row) {
// Get the "data" block
$entry = $row['data'];
// Start your temporary array
$each = [
'article title' => $entry['articleTitle'],
'publication title' => $entry['pubTitle'],
'key' => $row['key']
];
// Get each author's name
foreach ($entry['authors'] as $i => $author) {
$each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
}
// Append it to your output array
$output[] = $each;
}
print_r($output);
Example: https://eval.in/369313
Have you tried to use array_map ?
That would be something like:
$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
return implode(', ', array_map(function ($author) {
return $author['firstName'];
}, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));