So what I have here is a JSON response from my PHP cURL, so I'm trying to get the specific group of array under location depending where is the identifier value I'm checking.
{
"status": "SUCCESS",
"response": {
"offset": 0,
"max": 50,
"count": 2,
"locations":[
{
"identifier":"54320",
"id": 503892,
"name":"The Foo"
},
{
"identifier":"54321",
"id": 503893,
"name":"The Bar"
}
]
}
This is what I've done so far and what I'm trying to do. So I already parse the json above and put it on foreach. Note the identifier is not always an int it can also be string.
$parsed_json = json_decode($phpCurlResponse, true);
$parsed_json = $parsed_json["response"]["locations"];
foreach($parsed_json as $key => $pj){
if($pj['identifier'] == "54320"){
echo $pj['name'].' & '.$pj['id'];//this should display The Foo & 503892
}
}
I have tried this one and it can only see the first group of array under locations but when I change the identifier value from 54321 to 112233 the response will be Identifier do not exist. can you help me how we achieve this.
Your JSON is invalid.
There shouldn't be a comma after the last object in the locations array.
There should be a } after the locations closing array bracket (]).
So is the valid JSON.
{
"status": "SUCCESS",
"response": {
"offset": 0,
"max": 50,
"count": 2,
"locations": [
{
"identifier":"54320",
"id": 503892,
"name":"The Foo"
},
{
"identifier":"54321",
"id": 503893,
"name":"The Bar"
}
]
}
}
Sorry for the premature posting but I want you to know that there's nothing wrong with the code above its just had some typo error on the json response I typed, anyways thank you for the help guys. :) So that's one possible way to get an specific set of array inside an object depending where's the key value you looking for.
Related
I have a use defined json string inside a database.
The JSON string has lots of levels. I know my user will define a kay called "basevalue" and place it somewhere in the json.
The problem is, I don't know ahead of time where in the JSON it will be placed, and every use is likely to place is in different places in the array, perhaps at different levels.
This is an example of the JSON data being saved by the user:
{
"name": "",
"type": "layout",
"children": [
{
"name": "",
"type": "section",
"children": [
{
"name": "",
"type": "row",
"children": [
{
"name": "",
"type": "column",
"props": {
},
"children": []
},
{
"type": "column",
"children": [
{
"type": "itemdata",
"props": {
**"basevalue": "100",**
},
"children": []
}
]
}
]
}
]
}
I'm converting this data to an array using json_decode:
$json = json_decode($json, true);
No I need to search through the array, and find the key of 'basevalue' and then get whatever value the user has input, in the case above that would be '100'.
So to the issue is, I have no idea what 'node' the 'basevalue' key will be. It could be 40 deep, it could be in the first 'children' node.
This is up to the user.
So how do I take any version of the JSON string about and return the '100'?
Many thanks.
You can recursively iterate over the data and get the value of the key basevalue. To make this search faster, we can adopt an early exit approach similar to breadth first search. By this, we call add all values who are arrays in a queue and continue our search for the key basevalue and later on deal with pending queue. This would be faster than basic recursion because a lot of times it's possible that key was on the same level but we searched all the way down on all other trees which proved out to be trivial.
Snippet:
function getBaseValue($arr,$search_key){
$pending_calls = [];
foreach($arr as $key => $value){
if(is_array($value)){
$pending_calls[] = $value; // queue them for later judgement
}else if($search_key === $key){
return $value;
}
}
foreach($pending_calls as $call){
$returned_val = getBaseValue($call,$search_key);
if($returned_val !== false) return $returned_val;
}
return false;
}
echo getBaseValue($arr,'basevalue');
Demo: https://3v4l.org/gdLK1
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);
I'm working with the Zoho CRM. The response format I get from their API seems a bit odd to me; I can't just pull an object from it like I would normally. I'm trying to parse the results using PHP. Here's an example of their response formatting:
{
"response": {
"result": {
"SalesOrders": {
"row": {
"FL": [
{
"content": "6666666000000000000",
"val": "SALESORDERID"
},
{
"content": "Order",
"val": "Subject"
},
{
"content": "Pending",
"val": "Status"
},
{
"content": "John Smith",
"val": "Order Owner"
},
{
"content": "Canada",
"val": "Billing Country"
},
{
"product": {
"FL": [
{
"content": "5555555000000000000",
"val": "Product Id"
},
{
"content": "Roller Coaster",
"val": "Product Name"
}
],
"no": "1"
},
"val": "Product Details"
},
"content": "Pending",
"val": "Ticket Status"
}
],
"no": "1"
}
}
},
"uri": "/crm/private/json/SalesOrders/getRecordById"
}
}
What I'm trying to do is get the Product ID of the Product (in this case the value is "5555555000000000000".
Every response has the same structure, but I can't use the index to parse out the key/value because the amount of fields could change between API calls (meaning the index of product could be 5, like above, or 7, or 8, or whatever depending on the amount of fields being pulled in). I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)? That's the only way I could think of and it doesn't seem very efficient.
PHP has a function for that: json_decode. See http://php.net/manual/en/function.json-decode.php
$response = "... your JSON response from wherever ...";
$data = json_decode($response, true);
// Access the nested arrays any way you need to, such as ...
$orders = $data["response"]["result"]["SalesOrders"];
foreach ($orders["row"]["FL"] as $item) {
if (array_key_exists("product", $item) {
echo $item["product"]["FL"][0]["content"];
}
}
EDIT: Corrected 2nd arg to json_decode (thanks Marcin)
I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Yes, there could be a key=>value pair, but that would be to easy.
Because Zoho ... ;)
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)?
No, (even if you turn this into an array using json_decode($data, true) and go forward by using named keys) you end up iterating or testing for key existence (need to get to product-FL-val to get product-FL-content). Maybe array_fiter or array_walk with a callback come to rescue, but they also iterate internally.
My suggestion is to simply safe some time and use an existing package, e.g.
https://github.com/cristianpontes/zoho-crm-client-php
or search one on Packagist https://packagist.org/search/?q=zoho
I dont know this might help or not. But this is what i am using for my Zoho APP. Actually I am developing a PHP app using Zoho. Your JSON and mine is same but i am getting Deals and you are fetching SalesORders.
<?php
$token = $_SESSION['token'];
$url = "https://crm.zoho.com/crm/private/json/Deals/getRecordById?authtoken=$token&scope=crmapi&id=$dealID";
$result = file_get_contents($url);
$deal_detail = json_decode($result);
$deal_detail = json_decode(json_encode($deal_detail), True);
$deal_detail_array = array();
//Instead of Deals you have SalesOrder right
foreach($deal_detail['response']['result']['Deals']['row']['FL'] as $array){
$deal_detail_array[$array['val']] = $array['content'];
}
echo $deal_detail_array['DEALID']; // You can change this to SALEORDERID, get data correctly every time.
echo $deal_detail_array['Deal Name'];
echo $deal_detail_array['Amount'];
///.......and so on ..............//
//................................//
Only the difference between your JSON and mine is: You have "SalesOrders" in your JSON after result field and in my json instead of SalesOrders i have Deals there.
this code is working fine for me. SO you can do same thing except a field update. I am getting DEALID correctly for each request similarly you can get you SALESORDERID
How do I access webm->max in this Steam API? It's the order [{ that confuses me, array of one before object? I'm not quite sure about the targeting here..
I've tried:
$gameTrailer = $game_json->57690->data->movies[0]->webm->max;
and
$gameTrailer = $game_json['57690']['data']['movies']['webm']['max'];
The API text is like this:
"movies": [{
"id": 2029441,
"name": "Tropico 4 Gameplay Trailer",
"thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie.293x165.jpg?t=1447358847",
"webm": {
"480": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie480.webm?t=1447358847",
"max": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie_max.webm?t=1447358847"
},
"highlight": true
}],
and "movies" lies within:
{"57690": {
"data": {
Assume I'll always want the very first movie in an array (which in this case is an array of one). Thanks in advance.
Correct syntax:
$game_json->{57690}->data->movies[0]->webm->max
When you have an object with a numeric key, you have to wrap the key name by curly brackets (Numeric keys are not valid property names).
If you use the associative option:
json_decode( $data, True );
your second attempt is almost right. Simply add the correct index after movie:
$gameTrailer = $game_json['57690']['data']['movies'][0]['webm']['max'];
I have the following json data:
{
"data": [
{
"name": "The Frugalicious Chef",
"category": "Chef",
"id": "186397894735983",
"created_time": "2011-03-07T16:10:35+0000"
},
{
"name": "Siuslaw Broadband",
"category": "Telecommunication",
"id": "190373850988171",
"created_time": "2011-03-06T20:21:42+0000"
},
{
"name": "Paul",
"category": "Movie",
"id": "129989595478",
"created_time": "2011-03-04T19:55:18+0000"
},
{
"name": "Mark Zuckerberg",
"category": "Public figure",
"id": "68310606562",
"created_time": "2011-02-16T09:50:35+0000"
},
The idea here is that I want to take this data and use parts of it. I want to create a list of the "category's" that are in the data. The problem is that there is and will be multiple items with the same category. So my list will have duplicates that I do not want. The following is how I am getting the data and converting it for use:
$jsonurl = "https://xxxxxxxxxx.com/".$fd_ID. "/info?access_token=".$session['access_token'];
$likesjson = file_get_contents($jsonurl,0,null,null);
$likesArray=json_decode($likesjson);
I then use a foreach to access the data.
foreach($friendLikesArray->data as $l)
{
etc......
}
So I guess muy question is I want to take the $likesArray and pull out all the unique Data->Category->names. Also will want to do sorting, and other things but I will get to that when the time comes.
Thanks for the help in advance.
Neil
The data structure you would want to use is a set, that only allows unique entries.
A simple implementation using PHP arrays is to use the keys.
e.g.
$categories = array();
foreach($friendLikesArray->data as $l)
{
$categories[$l->category] = true;
}
$categories = array_keys($categories);
This way if the category has already been added, then you are not adding anything new to the array.
If the keys are not important to you then you can use the line:
$categories[$l->category] = $l->category
But this means your array won't have 0,1,2...n for keys.