I have a json file with the following syntax:
[
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "asd23f",
"status": "Active",
"perCode": "1",
"idCode": "0987",
"nextCode": "09"
},
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "789096",
"status": "Active",
"perCode": "1",
"idCode": "076543",
"nextCode": "09"
}
]
I would like to use a for loop in order to add something like a userID before or after the nextCode. Is there any solution to this?
So far, I tried this:
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $key=>$c)
{
if (is_array($c))
continue;
$data .= $data . "user_id:$userId";
}
}
Of course it does not make the trick, any ideas please?
There are a few problems.
First, the foreach loop works with a copy of the array it's iterating, so modifying one of the items there won't change the original array.
Then, your inner foreach loop is overwriting the $key from the outer loop. That would cause problems, but it's okay, because you don't actually need the inner loop.
Finally, after you've decoded the JSON string, $data will be an array, so appending to it with .= won't work, and even if it did, you'd just be sticking something on the end of it rather than at the specific point where your loop is.
Just refer to the specific key you need and set the value there.
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
$data[$key]['user_id'] = $userId;
}
$data = json_encode($data);
Another way which is slightly shorter is pass the value by reference &:
$data = json_decode($file, true);
foreach ($data as &$val) {
$val['user_id'] = $userId;
}
https://3v4l.org/ZF4Ve
This is how you can add an element to a parsed JSON and recostruct it back into a JSON:
// parse the JSON into an array
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
// add the userID to each element of the main array
// it will be inserted after the last element (after nextCode)
$data[$key]['userID'] = 'some-id';
}
// if needed, parse the array back to JSON
$data = json_encode($data);
I explain to you
The following expression converts the information from string to array
$data = json_decode ($file, true);
So in your foreach you only have to add the key
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $k=>$c)
{
if (is_array($c))
continue;
$data[$k]['user_id'] = $userId;
}
}
I see everybody answered for array options. I don't see why not using object, though.
I would do it like this:
$data = json_decode($file);
foreach ($data as &$field)
{
$field->userID = $userId;
}
$data = json_encode($data);
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
`{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}`
I am trying to get the value of rno using PHP code
`$data = json_decode($json, true);
foreach ($data as $item) {
$name = $item['name'] ;
$number= $item['rno'] ;
}`
#Sahil Gulati's code is more prefect and right way to parse the json in php
here is an other way to parse the json data in php
<?php
$data = json_decode($json, true);
foreach ($data as $item) {
foreach ($item as $val) {
echo $name = $val['name'];
echo $number = $val['rno'];
}
}
?>
the above code that i have shared you can understand easily. but after learning that how to parse json data in php you should use #Sahil Gulati's mathod.
Change this to:
foreach ($data as $item)
This:
foreach ($data["student"] as $item)
Try code snippet here
PHP code:
<?php
ini_set('display_errors', 1);
$data = json_decode($json, true);
foreach ($data["student"] as $item)
{
$name = $item['name'];
$number = $item['rno'];
}
You should take a closer look at the structure of the json encoded data. That helps to implement a clean iteration:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
$output = [];
array_walk($data->student, function($entry) use (&$output) {
$output[] = $entry->rno;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => 187654
)
The output format has been chosen as an array, since the json structure suggests that multiple students can be contained.
If you are only directly interested in the rno property of the first entry in the student array, then you can access it directly:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
var_dump($data->student[0]->rno);
The output of that variant obviously is:
string(6) "187654"
I am facing a problem in php using CURL. I made a https request and I got response in multidimesional array.
[{
"id":"22622",
"name":"",
"email":"ffv7678#gmail.com",
"mobileno":"",
"birth_dt":"",
"marital_status":"",
"gender":"",
"educationid":"0",
"occupationid":"0",
"industryid":"0",
"incomeid":"",
"city":"0",
"state":"0",
"country":"0",
"postcode":"",
"deviceid":"805086099499488",
"regid":"",
"device_type":null,
"userstatus":"0",
"refcode":"D1219C92",
"new_user":"0",
"device_token":""
}]
Now I want to decode it and save the value of "id" in a variable.
$result=curl_exec($ch);
$books = json_decode($result, true);
echo ($books[0]['id']);
I tried the above code, but failed.
$books = json_decode($result, true);
foreach ($books as $book)
{
//$book carries info of books;
$id = $book['id'];
///... You can define other variables here
}
You need to use foreach() loop for this.
foreach ($a[0] as $key => $value) {
echo $key."<br>".$value;
if($key == 'id'){
$id = $value;
}
}
echo $id;
Also, if you just want to assign the value of id to another variable, you can just right
...
$no = $a[0]->id;
echo $no
...
instead of the foreach loop.
Can any one help me to read this type of json response.
{"\u0000*\u0000_translate":
{
"app_text_newcomer":"Newcomer",
"app_text_senior":"Senior",
"app_text_mostsenior":"Most Senior",
"app_text_results":"Result",
"app_text_result":"Result",
"app_text_agenda":"Agenda",
"app_text_dbvg":"Dbvg"
},
"0":{}
}
how can i get this value \u0000*\u0000_translate
Looks like JSON, so use json_decode to get a PHP object or associative array.
Edit: Having just tried it, I see your problem. json_decode() can't handle nulls in the data, so you should file a bug about that.
Workaround: Preprocess \u0000 to some sentinel value you can later replace for a real null, such as this:
$json = '{"\u0000*\u0000_translate": { "app_text_newcomer":"Newcomer", "app_text_senior":"Senior", "app_text_mostsenior":"Most Senior", "app_text_results":"Result", "app_text_result":"Result", "app_text_agenda":"Agenda", "app_text_dbvg":"Dbvg"}, "0":{}}';
$json = str_replace('\u0000', 'XNULLX', $json);
$arr = json_decode($json, true);
foreach ($arr as $k => $v) {
if (strpos($k, 'XNULLX') !== false) {
unset($arr[$k]);
$k = str_replace('XNULLX', "\0", $k);
$arr[$k] = $v;
}
}
echo var_export($arr, true);
I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);