Multidimensional array JSON PHP iteration - php

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").

Related

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);

"Nested" array within db response using Codeigniter

I am trying to create a "nested" array within an object that I am returning from a database.
I can have more than one footnote per "thing".
This is what I am currently getting back:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnote_id": "1",
"footnote_text": " Footnote one"
}]
}
Here is the result I'm trying to generate:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnotes": [{
"footnote_id": "1",
"footnote_text": " Footnote one"
},
{
"footnote_id": "2",
"footnote_text": "Footnote two"
}]
}]
}
I have a footnotes table that has all kinds of footnotes (footnote_id and such).
I have a type table that has all kinds of things in it (type_id and such).
I also have a type_footnotes table that only has two columns: type_id and footnote_id
I'm not sure how to create the footnotes property of the response object - then display the results within that array.
Thank you for your time!
EDIT
Here is the query - I thought I had posted this as well. My apologies.
PHP
public function get_thing($type_id) {
$this->db->select('type.type_id, type.type, type.type_color');
$this->db->join('footnotes', 'footnotes.footnote_id, footnotes.footnote_text');
$this->db->join('type_footnotes, type_footnotes.type_id = type.type_id');
$query = $this->db->get_where('type', array('type.type_id' => $type_id), 1);
if ($query->num_rows() > 0) {
return $query->result();
}
}
Remove the limit, and post here what do you get as result :
$query = $this->db->get_where('type', array('type.type_id' => $type_id));

Comparing JSON arrays by a specific key in PHP

I want to use the data from array A (below), but only when the item ID from array A does NOT match an ID from items in array B (also, below). How would I go about comparing these two JSON array's by the key of ID (from items) via PHP? I imagine I first need to convert them with json_decode, but I'm not sure where to go after that?
Please note that array B has more nests ("items", "something", & "posts"), unlike array A. I want to compare the ID from items, not posts.
Array A:
{
"data": [{
"category": "Games",
"id": "45345"
},
{
"category": "Music",
"id": "345345345"
},
{
"category": "Food",
"id": "1"
},
{
"category": "Pets",
"id": "13245345"
}]
}
Array B:
{
"data": {
"something": "blah",
"posts": [{
"id": "34241",
"title": "orange"
}],
"items": [{
"id": "1",
"name": "orange"
},
{
"id": "2",
"name": "dog"
},
{
"id": "3",
"name": "cat"
},
{
"id": "4",
"name": "apple"
}]
}
}
With the case above, it would run through array A and output everything from array A except for the third item, since the id of that item (1) matches one of the id's in array B items.
Based on my understanding, you need a two step process. The first is extracting the ids from the first JSON blob, and the second is filtering the second JSON blob. So basically, we have map and filter. And it just so happens we can use PHP's inbuilt functions for this:
$ids = array_map(
function($value) {
return $value['id'];
},
$array2['data']['items']
);
First, we flatten the second array's items element into the individual ids. We "map" over the data.items array, and return the $id attribute of each array. Now, we have an array of ids...
$new = array_filter(
$array1['data'],
function($var) use ($ids) {
return !in_array($var['id'], $ids);
}
);
Now, we use that to filter the first blobs array to determine if an element is new or not. So we use array filter to handle it for us. All we need to do is check the $ids array to see if the current data's id is there (and if it is, throw it away). So we want to filter the array to be only variables that are not in array of $ids (hence !in_array($var['id'], $ids)...)
Decode the items into PHP arrays. Use a SPL like array_diff() to get the results of a diff comparison.
Referances to get you started:
http://www.php.net/manual/en/function.array-diff.php
http://php.net/manual/en/function.array-diff-key.php
http://www.php.net/manual/en/function.json-decode.php
Should be about what your looking for

Pull unique key names from json data, like SQL select distinct from**********

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.

Json Traverse Problem, not able to traverse values

I m getting the below return from ajax call but not able to traverse it please please help.
{
"1": {
"tel1": null,
"status": "1",
"fax": "",
"tel2": null,
"name": "sh_sup1",
"country": "Anguilla",
"creation_time": "2010-06-02 14:09:40",
"created_by": "0",
"Id": "85",
"fk_location_id": "3893",
"address": "Noida",
"email": "sh_sup1#shell.com",
"website_url": "http://www.noida.in",
"srk_main_id": "0"
},
"0": {
"tel1": "Ahemdabad",
"status": "1",
"fax": "",
"tel2": "Gujrat",
"name": "Bharat Petro",
"country": "India",
"creation_time": "2010-05-31 15:36:53",
"created_by": "0",
"Id": "82",
"fk_location_id": "3874",
"address": "THIS is test address",
"email": "bp#india.com",
"website_url": "http://www.bp.com",
"srk_main_id": "0"
},
"count": 2
}
You can do it very easily:
for(i = 0; i < msg.count; i++) {
alert(msg[i]['name']);
}
But the structure of your JSON object is not that good for several reasons:
It does not reflect the structure of the actual data
With this I mean, that you actually have an array of objects. But in your JSON object the elements of the array are represented as properties of an object.
You have invalid JavaScript object property names.
Properties for objects in JavaScript are not allowed to start with numbers. But with msg = { "1": {...}} you have a number as property.
Fortunately it is not that bad because you can access this property with "array like" access msg["1"] (instead of the "normal way", msg.1). But I would consider this as bad practice and avoid this as much as possible.
Hence, as Matthew already proposes, it would be better to remove the count entry from the array on the server side, before you sent it to the client. I.e. you should get a JSON array:
[{
"tel1": "Ahemdabad",
"status": "1",
// etc.
},
{
"tel1": null,
"status": "1",
// etc.
}]
You don't need count as you can get the length of the array with msg.length and you can traverse the array with:
for(var i in msg) {
alert(msg[i].name);
}

Categories