JSON decode in php web programming - php

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.

Related

how to print json decode api data in laravel

i want to print data which is coming from api when i print data it print only one data at a time how to print all these data in foreach loop i am using this but not work and getting and error Trying to get property 'Name' of non-object how to solve this problems thanks in advance
this is the response
this is my code
$response = sabreApiCall($url, $data_array);
$results = json_decode($response);
$i =0;
foreach ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult[$i] as $hotel)
{
echo $hotel->Name;
$i ++;
}
}
Just return $results as laravel will return it as json.
why are you using $i variable to loop through this array. Simply use foreach like this
$response = sabreApiCall($url, $data_array);
$results = json_decode($response);
foreach ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult as $hotel)
{
echo $hotel->Name;
}
}

How to add data in JSON using PHP

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

Printing json data

I have this json "https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json"
and I decode it with $data = json_decode($json, true);
But when I try to print the Vehicle part foreach($data['vehicle'][0] as $p)
{echo $p;}
the system prints"Invalid argument supplied for foreach()" and "Undefined index".
I'm a newbie, so forgive me.
Edit:This worked very well foreach ($data['decode']['vehicle'][0] as $p) echo $p;, but now I wonder if I can know the key or index of the element $p on every loop, as example "body>driveline>engine>id"...
the path is like these;
foreach ($data['decode']['vehicle'][0] as $p) echo $p;
You may want to to use:
$json = file_get_contents("https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json");
$obj = json_decode($json, true);
foreach($obj["decode"]["vehicle"] as $vehicle )
{
echo $vehicle['body'];
echo $vehicle['engine'];
# etc...
}
For accessing output in json file there is decode as root key. So first access decode key then after use vehicle information.
Below is code for that:
$data = json_decode($json, true);
$json = $data["decode"]["vehicle"][0];
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}

PHP - Getting array element from Json

I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/
I'm trying to get the tags[{"name":""}] part of it. For example, I would want the 'container', from '"name":"Container"'
This is my code here:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}
tags[] is an array, though I did tags[1], I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.
The simplest way may be to do an extra loop to grab all the name elements:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
foreach($mydata->tags as $tag) {
echo $tag->name;
}
}
or to get the first name of each tag group:
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[0]->name;
}
I updated the whole answer:
$json = json_decode($data, true);
if (isset($json['rgDescriptions']) && is_array($json['rgDescriptions'])){
foreach ($json['rgDescriptions'] as $array_no => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'])){
echo "{$array_no}::::";
foreach ($json['rgDescriptions'][$array_no]['tags'] as $k => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'][$k]['name'])){
echo "{$json['rgDescriptions'][$array_no]['tags'][$k]['name']},";
}
}
echo "<br />";
}
}
}

Decoding json in array , editing array and encoding in json - PHP

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :
$json = json_decode(file_get_contents('all_json_files/jobs.json'), true);
foreach ($json as $key=>$row){
foreach ( $row as $key=>$row){
foreach ( $row as $key=>$row){
foreach ($row as $key=>$row){
if(strcmp($key,"security_block")==0)
{
foreach ($row as $k=>$r){
if(strcmp($k,"job_payload_hash")==0)
{
$row[$k]['job_payload_hash']=$base64String;
print_r($row);
}
}
}
}
}
}
}
print_r($json);
Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .
If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}
You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of #Ja͢ck .
this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result.
Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);

Categories