I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer
Related
I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>
{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}
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 />";
}
}
}
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);
I have a json string like this:
$fields_string = '
{"fields":
{"customers":[{"name":"john","id":"d1"},
{"name":"mike","id":"d2"},
{"name":"andrew","id":"d3"},
{"name":"peter","id":"d4"}]
}
}'
How can I print each name? I will use them later in a html select options, I know how to do that. But I couldn't get the string out.
Here are something I tried:
$obj = json_decode($fields_string);
$fields_detail = $obj-?{"fields"}->{"customers"};
at this point, I am able to print the customer array out by echo json_encode($fields_detail), but before that, I want to get the name break down using foreach. I tried several times, it didn't work. Can anyone help please.
Thanks!
Customers is an array of objects so iterating over each object and reading the property should work.
foreach ($fields_detail as $customer) {
echo $customer->name;
}
Something like this:
$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
echo $customer['name'];
}
Access the names via fields->customers:
$obj = json_decode($fields_string);
foreach($obj->fields->customers as $customer)
{
echo $customer->name . "\n";
}
Demo
foreach($obj->fields->customers as $fields)
echo $fields->name;