Parse a multi level json in php - php

I have this json file and I would like to get back "host_name" values for all items. Below, my php code, I tried some things, using true to decode json in an array or without it and use a foreach(), but I can't do it.
{
"href": "https://webservice:8080",
"items": [
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server1"
},
"href": "https://server1:8080"
},
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server2"
},
"href": "https://server2:8080"
},
{
"Hosts": {
"cluster_name": "cluster1",
"host_name": "server3"
},
"href": "https://server3:8080"
}
]
}
Here is my php code. Would like to do it as simple as possible. My goal is to use last values of a json ('host_name') to display all of them.
<?php
$content = file_get_contents("test.json");
$content = utf8_encode($content);
$result = json_decode($content, true);
var_dump($result);
echo "<br><br><br>";
#echo $result["items"]["Hosts"][0]["host_name"];
foreach($result as $r) {
echo $r['items']['Hosts']['cluster_name'].'<br>';
}
?>
Thanks.

You are just looping over the wrong array, it should be
foreach($result['items'] as $item) {
echo $item['Hosts']['host_name'];
}

$result need to be $result['items']
foreach($result['items'] as $r) {
echo $r['Hosts']['cluster_name'];
echo PHP_EOL;
}
Output:- https://eval.in/837593

As mentioned above, you are looping through the wrong array. You can loop through the object like this as well:
$obj = json_decode(utf8_encode(file_get_contents("test.json")));
foreach($obj->items as $item)
{
var_dump($item->Hosts->host_name);
}

Just to show an alternative method, you can use array_column() and implode() to omit the trailing <br> that will be displayed with the foreach loop methods.
Code: (Demo)
$items=json_decode($json,true)['items'];
echo implode("<br>",array_column(array_column($items,'Hosts'),'host_name'));
Output:
server1<br>server2<br>server3

Related

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.

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

Parsing JSON in PHP to extract lat/lon

I need to parse this JSON using PHP
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.91138,
"lng": 7.671783
},
"name": "Corso Vinovo, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.909979,
"lng": 7.676234
},
"name": "Il Tempio del Pane, Corso Cesare Battisti, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.907805,
"lng": 7.674952
},
"name": "Banca Intesa, Via Ferdinando Salotto, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}]
to extract the coordinates in lat / lon.
What have I to use after
echo $wayPoints->?????
and how I create a for cicle to extract all the coordinates?
Any help will be appreciated!!Thank you!
Cesare
EDIT: a code sample (note that the JSON come from a POST parameter ...)
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints);
foreach($json as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
?>
so should be more clear ... (the code NOT working ...)
Thank you again ...
EDIT 2: this code work !!!
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints, true);
foreach($json as $f){
echo "</br>";
echo $f['latLng']['lat'];
echo "</br>";
echo $f['latLng']['lng'];
echo "</br>"; }
?>
the output is
44.91138
7.671783
44.909979
7.676234
44.907805
7.674952
Thank you all!
This will convert your json object into an associative array, then iterate with foreach.
//use json_decode in associative mode
$decoded = json_decode($json, true);
//Your object is now an array called $decoded
//Your locations are subarrays of $decoded
//The co-ords are subarrays of each $locationArray
foreach($decoded as $locationArray)
{
echo "The co-ordinates for {$locationArray['name']} are: {$locationArray['latLng']['lat']},{$locationArray['latLng']['lng']}" . PHP_EOL;
}
First you need to do $file = json_decode()
and then the file you get just add to foreach:
foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}

Foreach getting value null, why?

I am trying to get access to some data in PHP. If I print my docuements as a JSON object I get the document like so:
print_r($url);
[
{
"channel": "hello.com",
"partone": {
"click": 30580,
"load": 2156552
},
"parttwo": {
"click": 3274,
"load": 402327
},
"partthree": {
"click": 406467,
"load": 903869
}
}
]
So my main idea is to get the "click" of "parttwo" but I am getting null. This is my PHP code where I am making the mistake:
foreach ($url[0]['parttwo'] as $obj) {
$doc = array();
$doc['click'] = $obj['click'];
$param []= $doc;
}
Fo that data, simply:
$array = json_decode($url, true);
$param = $array[0]['part2']['click'];
If you really need to loop then:
foreach($array as $value) {
$param[] = $value['part2']['click'];
}

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