Looping through JSON fails with json_decode - php

I am pulling JSON data from a URL and attempting to display a list of just the display names.
In a way, this would be very easy too loop through if I knew that X amount of results would return each time. However, the results returned will vary from 0 to 50+.
I have done plenty of searches that all say "just use json_decode"... not so much the case.
I have the following JSON:
{
"ACK": "SUCCESS",
"ERROR": null,
"AGENT": {
"has_results": 1,
"agents": [
{
"display_name": "Alex",
"time_in_state": "5214",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Bill",
"time_in_state": "6312",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Carrie",
"time_in_state": "5982",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "David",
"time_in_state": "4226",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
}
]
},
"SKILL": {
"has_results": 1,
"num_skills": 1,
"skills": [
{
"display_name": "Phone Skills",
"skill_num": "76",
"callsinqueue": "0",
"callstoday": "9",
"abandtoday": "0",
"lwt": "0",
"ewt": "0",
"servicelvl": "100",
"avgspeedans": "6",
"talktime": "289"
}
]
},
"TIME": 1383766541
}
From the examples and documentation I have read, the following code has been created:
<?php
$url="http://myjsonurl.local";
$json = file_get_contents($url);
//echo $json;
$json = json_decode($json);
foreach($json as $item->display_name)
{
echo $item->agents->display_name;
}
?>
My end goal is to have a list of only names which I can then display in an alternate webpage.
So my question is... how do I read this page and format the data nicely (perhaps an array I can just print?) so I can utilize it in the future?

You have the following in your code:
foreach($json as $item->display_name)
This is incorrect and doesn't do what you want. As you can see by doing a print_r($json), the names are in $json->AGENT->agents, so you'll want to loop through those items and then traverse the display_name using arrow syntax ($item->display_name). Once you have the display name, you can push it into an array, and use it however you want.
Your loop should look like below:
$names = array(); // initialize empty array
foreach($json->AGENT->agents as $item)
{
$names[] = $item->display_name;
}
print_r($names); // see the array contents
Output:
Array
(
[0] => Alex
[1] => Bill
[2] => Carrie
[3] => David
)
Demo.
Note: If you don't know the structure of the JSON object beforehand, then you can use a nested foreach loop to retrieve the names.

The array you want to iterate is $json->AGENT->agents. Also, your foreach syntax is wrong.
Try:
foreach($json->AGENT->agents as $item)
{
echo $item->display_name;
}

If you want to get the JSON data as an array rather then an object, use json_decode($json, true) instead. This tells the function to return it as an associative array, as you can read here: http://php.net/manual/en/function.json-decode.php

You have an error in your foreach loop.
foreach($json as $item->display_name)
{
echo $item->agents->display_name;
}
$item is not an object and you are actually trying in this line to access property "display_name" of none object ($item)
foreach($json as $item)

Related

How to filter data properties coming from API in PHP?

I have this data coming from an API, the tmdb api, and I want to create an api to filter the data and expose just the properties I need. In this case I just want my endpoint to expose id, title, and overview and nothing else. How can filter these properties with PHP in order to get and expose just the properties I need?
"results:[{
"vote_count": 779,
"id": 420817,
"video": false,
"vote_average": 7.2,
"title": "Aladdin",
"popularity": 476.676,
"poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
"original_language": "en",
"original_title": "Aladdin",
"genre_ids": [
12,
14,
10749,
35,
10751
],
"backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
"adult": false,
"overview": "A kindhearted street..."
}],
The expected result should be:
myapi.com/api
"results:[{
"id": 420817,
"title": "Aladdin",
"overview": "A kindhearted street ..."
}],
$json = json_decode($data);
$results = $json->results;
$results= array_map(function($r){
return ["id" => $r->id, "title" => $r->title, "overview" => $r->overview]
}, $results)
echo json_encode($results);
You can filter the array like this:
function myFilter($result) {
$filtered_array = array();
foreach($result as $movie) {
$filtered_movie = array();
$filtered_movie['id'] = $movie['id'];
$filtered_movie['title'] = $movie['title'];
$filtered_movie['overview'] = $movie['overview'];
array_push($filtered_array, $filtered_movie);
}
return $filtered_array;
}
Just pass the unfiltered array to the function and you'll get the filtered one back.
EDIT:
If your data is in JSON format you will need to use json_decode() to turn it in to an array in PHP. And if you want to return it as JSON then use json_encode() for that.

Search multidimensional array with Key name and return values as result

I am PHP beginner so please be patient with me. I spent couple of hours going through many threads already on multidimensional arrays search but none of them fits my situation. Sounds really simple but kind of stuck as I want to search by key name and retrieve values against it.
Tried some methods like array_column but returns an empty array.
I simply want to loop through array finding key name as: "largeImageURL" from all the array elements and want to return its values.
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}
First of all, you have to convert your JSON object to an array and compare like below.
$results = json_decode($your_array);
$match_result = [];
foreach($results['hits'] as $result) {
if (isset($result['largeImageURL']) {
$match_result [] = $result['largeImageURL'];
}
}
print_r($match_result);
You have to decode your JSON response into an array and loop through hits array till you find the key and return the data.
$returnArr = array();//to store values of largeImageURL
$json = "<json response>";//your json string here
$decoded_json = json_decode($json, true);//convert json to an array
//now we will loop through hits
foreach($decoded_json['hits'] as $hit){
$returnArr[] = $hit['largeImageURL'];
}
print_r($returnArr);

How to save data through objects which are in array in Laravel

I m newbee in laravel. I am sending such type of response through Postman. and in Laravel controller I m getting this response in $request.
[{
"id": 40,
"cname": "Ramesh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "111",
"input2": "111"
}, {
"id": 45,
"cname": "Suresh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "222",
"input2": "222"
}, {
"id": 49,
"cname": "Raj",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "333",
"input2": "333"
}]
I am facing difficulty in
How to count the total no of objects in array which I am receiving in $request. I had used count($request) or sizeOf($request) but its returning only 1 although there are 3 arrays. Help me in this.
How to save the data in database through such arrays.I want to save the values of input and input2.
Probably late, but may help someone in the future. First of all. You need to iterate over the array of objects like so
foreach($request->all() as $key => $value){
$model = new Model();
$model->attribute1 = $value['attribute1'];
$model->attribute2 = $value['attribute1'];
$model->attributeN = $value['attributeN']; // where N is infinite # of attr
$model->save();
}
So what is happening is that each time the loop iterates, it create a new object of your Model type inside the loop and assigns the objects attributes from the array key values and persists in DB and repeats until all the objects in the array are finished. The
$model = new Model();
is necessary so that each time loop iterates It creates a new object and persists. The loop may save only one object if u do not create it each time the N iteration occurs. This may happen if u are creating the model object in the constructor where it is instantiated once when the constructor is run.
Hope this helps.
Try to convert it to an array:
$data = json_decode($request, true);
$count = count($data); // Count number of elements.
Model::insert($data); // Insert all elements into DB.
Don't forget to validate any input first and add all fields except timestamps to a $fillable array.
You can try this..
$data = [{},{}]; // your response
$count = 0;
foreach($data as $obj)
{
Model::create($obj); //save the model
$count ++;
}
echo $count // your count
its quit simple
$request ='[ {"id":40,"cname":"Ramesh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"111","input2":"111"}, {"id":45,"cname":"Suresh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"222","input2":"222"}, {"id":49,"cname":"Raj","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"333","input2":"333"}]';
$request = (array)json_decode($request, true);
now use them as you usually use .
I got the solution. I was making mistake in sending the data from angularjs.I was directly sending the POST request without creating its object like var data = { 'data':my_request} .That is why request was reeving with instance in laravel. But, as I start sending data by creating its object its working. This was the solution for my first problem. Help me how to store that received data in database.

Multidimensional array JSON PHP iteration

Here is my JSON file which is called (inventory.json). How do I parse the json so I can get all of the inventory's tag_name in the "Descriptions" array? Since the Inventory array's classid points out to the description's id/classid, it seems possible to get each of the inventory's tag from the description but I have no idea to do it.
I read something about recursive array iterator and for each but I have no idea which one is appropriate in this circumstance. I am very new here so please be kind! Thank you.
{
"Inventory": {
"7905269096": {
"id": "7905269096",
"classid": "771158876",
"instanceid": "782509058",
"amount": "1",
"pos": 1
},
"7832200468": {
"id": "7832200468",
"classid": "626495772",
"instanceid": "1463199080",
"amount": "1",
"pos": 2
},
"7832199378": {
"id": "7832199378",
"classid": "626495770",
"instanceid": "1463199082",
"amount": "1",
"pos": 3
},
"Descriptions": {
"771158876": {
"classid": "771158876",
"instanceid": "782509058",
"tags": [{
"tag_name": "unique",
"name": "standard"
}]
}
}
}
}
Your JSON string is invalid, but hopefully this answer will lead you on the right path to your desired result.
First, make it into a PHP array:
$jsonArray = /* your json array */;
$phpArray = json_decode($jsonArray, true);
Then you can iterate through one of the arrays (the "Inventory" one) and find the relevant tag name:
//Create a new array to hold the key=>value data
$combined = [];
foreach($phpArray["Inventory"] as $i => $v){
//Find the relevant key in the Descriptions array and
//push this information information to the $combined array
$combined[$i] = $phpArray["Descriptions"][$i]["tags"]["tag_name"];
/* The above is essentially the same as
$combined["7905269096"] = "unique"; */
}
Then, $combined will be a key/value array where the key is the ID (e.g. "7905269096") and the value will be the tag name (e.g. "unique").

Retrieve objects inside json array

I'm trying to retrieve team1 score however i cant seem to figure out how to output this. So far i've got this to work where $obj is the json output.
$obj->recent
JSON
"recent": [
[
{
"match_id": "64886",
"has_vods": false,
"game": "dota2",
"team 1": {
"score": "",
"name": "Wheel Whreck While Whistling",
"bet": "7%"
},
"team 2": {
"score": "",
"name": "Evil Geniuses DotA2",
"bet": "68%"
},
"live in": "1m 42s",
"title": "Wheel Whreck... 7% vs 68% Evil...",
"url": "",
"tounament": "",
"simple_title": "Wheel Whreck... vs Evil...",
"streams": []
}
]
You need to use json_decode(); This function returns proper object with arrays and objects inside. Now you need check what is an object and what is an array.
$obj = json_decode($obj, true);
$obj->recent; //array
$obj->recent[0]; //first element of array
$obj->recent[0][0]; //first element of second array
$obj->recent[0][0]->{'team 1'}; //access to object team 1
$obj->recent[0][0]->{'team 1'}->score; //access to property of object team 1
You can find this helpful to understand what happens;
You can also check example on json_decode documentation
If you use var_dump function on $obj it will show you what is an array and what is an object.
You'll want to use json_decode to get that into an array. It looks like recent is an array of arrays of objects. So, you'll do something like
$json = json_decode($obj->recent, true);
$team1 = $json[0][0]['team 1']; //should return array
$score = $team1['score']
edit: Thanks for the comment, was missing a true as the second param in json_decode

Categories