PHP multilevel JSON decode - php

I try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.

Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI

Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array

You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!

Related

foreach loop in a multidimensional array

Trying to get the a certain parameter in my multidimensional array... I have the following api request:
$responeAPI= ClientCode::request('post', 'responeAPI', $responeAPI,['debug'=>true]);
foreach ($responeAPI["buDetail"] as $key => $value){
$businessUserDet = $value["name"];
}
$storage['enterpriseList'] = $businessUserDet;
}
The array from the API response is like this:
{
"buList": {
"buDetail": [
{
"businessUserId": 2,
"name": "SAMPLENAME_231",
"parentBusinessUserId": 1,
"profileId": 2,
"profileName": "Enterprise"
}
]
},
"resultCode": 0,
"transactionId": "responeAPIs_1577358460"
}
I need to extract the "name" so I can use it for the $options parameter. Right now, my code isn't showing anything.
You can do like this using array_column
$jsonArray = '{"buList":{"buDetail":[{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"},{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"}]},"resultCode":0,"transactionId":"responeAPIs_1577358460"}';
$detais = json_decode($jsonArray, true);
print_r(array_column($detais['buList']['buDetail'], 'name', 'id'));
http://sandbox.onlinephpfunctions.com/code/458592622c78c67771cbf2e54661b9294c91e710
Could you change this line
foreach ($responeAPI["buDetail"] as $key => $value){
to
foreach ($responeAPI["buList"]["buDetail"] as $key => $value){
You can invoke as an object:
$array = '{ "buList": { "buDetail": [{ "businessUserId": 2, "name": "SAMPLENAME_231", "parentBusinessUserId": 1, "profileId": 2, "profileName": "Enterprise" } ] }, "resultCode": 0, "transactionId": "responeAPIs_1577358460" }';
$array = json_decode($array);
//for debug purposes only
echo var_export($array, true);
echo $array->buList->buDetail[0]->name;
Output: SAMPLENAME_231

JSON Get the name of dynamically changing key with PHP

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.

How to iterate JSON using PHP?

Can any one tell me how to iterate below given JSON data using PHP,
{
"value1":"3",
"value 2":"5",
"Id":[
"210",
"211"
]
}
<?php $json='{ "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
$getarr=json_decode($json,true);
foreach( $getarr as $key => $value)
{
if(is_array($value))
{
// ID has an array so retrieve a value
foreach($value as $key1 => $value1)
{
echo $key."=>".$value1;
}
}else
{
echo $key."=>".$value;
}
} ?>
It will be produce the below output. Hope it will be helpful to solve your problem
Answer:
value1=>3 value 2=>5 Id=>210 Id=>211
Use json_decode function for converting it to array.
$array = json_decode( $json, true );
Copy and paste you can change the print out to fit your use
<?php
$bar=' { "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
//var_dump($bar);
$JSONdata = json_decode($bar, true);
//echo
$JSONdataValue="";
$JSONdataValue.=$JSONdata['value1']."<br>";
$JSONdataValue.=$JSONdata['value 2']."<br>";
$JSONdataValue.=$JSONdata['Id'][0]."<br>";
$JSONdataValue.=$JSONdata['Id'][1]."<br>";
echo $JSONdataValue;
?>

Get JSON from URL by PHP

I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);

json parsing with php foreach

I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}

Categories