Loop json object as array in PHP - php

How can i loop the response to get all ids and names?
If the response like this:
{
"Data": [
{
"Id": "4321",
"Name": "Dog"
},
{
"Id": "749869",
"Name": "Cat"
}
]
}
I can get all the ids and names using this code:
foreach (json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
But, if the response like this:
{
"Data": {
"dog": {
"Id": "4321",
"Name": "Dog"
},
"cat": {
"Id": "749869",
"Name": "Cat"
}
}
}
How can i get all the ids and names without knowing the amount of the array? Thank you.

You can get PHP to read everything into an (associative where applicable) array.
foreach (json_decode($response->content, true)["Data"] as $resp) { //2nd parameter is to decode as array
echo $resp["Id"];
echo $resp["Name"];
}
Example run: https://eval.in/954621
Alternatively you can do the lazy thing and just cast:
foreach ((array)json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}

Well if you want to extract all ids into one array (I assume you mean all into one array), to use in a database query as an example. I would recommend you doing like this.
$ids = array_values(array_map(function($animal){
return intval($animal['Id']);
}, json_decode($response->content, true)['Data']));
var_dump($ids);

you do the same ! foreach loop would work on both.
the json response supposed to have the same format every time, unless you have a really weird API.
<?php
$response = json_decode($json);
foreach($response as $animal => $data)
{
echo $animal;
echo $data->id;
echo $data->name;
}

Related

How to find json direct parent based on children value

I need to find the direct parent of all instance of "type": "featured-product" in a JSON file using PHP. store this parent string in a variable. use a foreach.
In the example below, the variable would have the value "1561093167965" and "3465786822452"
I'm a little lost, thank you for the help!
{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}
foreach ($json['current']['sections'] as $sectionName => $section) {
if ($section['type'] && $section['type'] == 'featured-product') {
$featuredId = $sectionName;
}
}
Another approach you can take is to create a new array containing only featured-products using array_filter and then extract the keys. From the docs:
If the callback function returns TRUE, the current value from array is
returned into the result array. Array keys are preserved.
$product_sections = array_keys(
array_filter($json['current']['sections'], function($val) {
return $val['type'] === 'featured-product';
}));
Demo
The problem in your original code is that your $featuredId variable is getting overwritten in each iteration of the loop, so when it ends its value will be the one of last element processed. If you have to deal with multiple values, you'll have to add it to an array or do the work directly inside the foreach. You can see the other answers for how to fix your code.
There is probably a cleaner way but this works using json_decode and iterating over the array with foreach
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$e=json_decode($json,true);
foreach($e['current']['sections'] as $id=>$a){
if($a['type']=='featured-product'){
echo 'the parent id is '.$id;
}
}
//change this with the real json
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$result = [];
$jsond=json_decode($json,true);
foreach($jsond['current']['sections'] as $k=>$v){
if($v['type']=='featured-product'){
$result[] = $k;
}
}

Using php foreach to get a second JSON Nested Array

I have a nested array from a json API that usually have zero, one, or two arrays.
I can get it so if the array is empty to display "N/A", and to display only the first ([0]) instance of the array.
However displaying the second array is tripping me up. I know I need to use the foreach to iterate through the PosTags (see below) array, so to extract each Tag value in the body of the foreach loop. However, I can't figure HOW to do this correctly.
My JSON:
[
{
"SectionDetails": [
{
"Description": "Course Description",
"Departments": "Department",
"Credits": "3.00",
"Meetings": [
{
"DOW": "Th",
"Dates": "08-31-2017 to 12-08-2017",
"Times": "03:00 PM - 05:30 PM",
}
],
"PosTags": [
{
"Tag": "HART-ANC"
},
{
"Tag": "ARCH-ARCH"
}
]
}
]
}
]
Current PHP:
$postag = "N/A";
if (isset($sectiondetails->{'PosTags'}))
{
if(!empty($sectiondetails->{'PosTags'})) {
$postag=$sectiondetails->{'PosTags'}[0]->{'Tag'};
}
}
Running a foreach loop like the following displays "Object of class stdClass could not be converted to string" on the line where echo tag is:
if (isset($sectiondetails->{'PosTags'})) {
if(!empty($sectiondetails->{'PosTags'})) {
$postag=$sectiondetails->{'PosTags'};
foreach ($postag as $tag) {
echo $tag;
}
}
}
Ideally I'd like HART-ANC, ARCH-ARCH to be displayed. Thoughts?

How to get json format for monogo db object [duplicate]

I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;
$customers = $db->customer->find();
i want to return $customers collection as json document to my HTML. How can i do this?
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.
This also will work. And you can customize your json as well.
$arr = array();
foreach($customers as $c)
{
$temp = array("name" => $c["name"], "phone" => $c["phone"],
"address" => $c["address"]);
array_push($arr, $temp);
}
echo json_encode($arr);
Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
"5587d2c3cd8348455b26feab": {
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
"5587d2c3cd8348455b26feac": {
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
}
So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);
This creates the same result as
$result = Array();
foreach ($customers as $entry) {
array_push($result, $entry);
}
echo json_encode($result, true);
which is an array of JSON objects
[
{
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
{
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
]

Decode json string PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I would like to get the values for 'datelog_collected' and 'value' fields:
{
"data": [
{
"datelog_collected": "2016-09-01 13:57:13",
"value": "36.06"
}
]
}
So far, i tried with json_decode but without success. I want this to stay as an object. Thanks
If you use
$object = json_decode($your_JSON_string);
datelog_collected and value will not be properties of the resulting $object.
The object will have only one property, data. data is a numerically indexed array (that is what the square brackets in the JSON mean) which contains one object. The properties you want belong to that object.
So you can get what you want with $object->data[0]->datelog_collected, etc.
If you use json_decode as:
$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }');
$res would be an object so you can access: $res->data
And if you add second parameter true (json as array)
$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }', true);
$res would be an array so you can access: $res["data"]
Try this
<?php
$datelog_collected=array();
$datelog_value=array();
$data='{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }';
$data_array=json_decode($data,true);//true create array if you want object then remove true
if(is_array($data_array)&&!empty($data_array))
{
foreach ($data_array as $key => $value) {
if(is_array($value))
{
foreach ($value as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
if($key2=="datelog_collected")
{
$datelog_collected[]=$value2;
}else{
$datelog_value[]=$value2;
}
}
}
}
}
//here is datelog_collected
var_dump($datelog_collected);
echo "<br/>-----------------------<br/>";
//here is datelog_value
var_dump($datelog_value);
}
?>
check working link http://main.xfiddle.com/7ffb488b/json_decoder.php

returning index from JSON returned array

Hi guys I was wonder how you can return the index based on ID with the following.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
for example, I want to get print the name based on ID. I've had a go at using array_search but it didn't like the structure of the array. I will be using it inside a sql loop and passing the ID from the query to return the name string from the array.
print $obj->{'data'}[0]->{'name'};
//where 0 is returned index based on a defined ID.
thanks a lot
The json_decode makes your variables into objects. To do a search, you could use:
// The extra true at the end makes it decode to associative arrays
$json = json_decode($friends, true);
findByName($json, 1234);
function findNameById($obj, $id) {
foreach($obj as $o) {
if($o['id'] == $id) return $o['name'];
}
return false;
}
You will need PHP 5.3 in order to utilize the following closure and enhanced ternary operator (prints name if record is found; otherwise, prints 'No record found.'):
$findById = function($id) use ($friends) {
foreach (json_decode($friends)->data as $friend) {
if ($friend->id === $id) return $friend->name;
}
return;
};
echo $findById('125930') ?: 'No record found.';
Nice thing about this is that you can pass this callable around and it will remember the scope it was defined with. This means that you can pass any ID but the $friends array will always be available to the closure.

Categories