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
Related
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);
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").
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));
I'm trying to remove an element from an array inside a collection. To remove the element, I have to look at the index (or date) field, and remove the one which has the lowest value. An example representation of my collection named "pages":
{
"_id": {
"$oid": "52e12df7e4b06e4ed65a554c"
},
"posts": [
{
"postId": {
"$oid": "52e12e5933a9fbec1100002d"
},
"date": 1390489177.267876,
"index": 1
},
{
"postId": {
"$oid": "52e12e5f33a9fb141800002c"
},
"date": 1390489183.277084,
"index": 2
}
],
"skillname": "Bilardo",
"skilltag": "Bilardo",
"currentIndex": 2
}
I need to remove this element from the posts array:
{
"postId": {
"$oid": "52e12e5933a9fbec1100002d"
},
"date": 1390489177.267876,
"index": 1
}
Whatever I would do, I could not manage to find the minimum "index" field in the array. The last php code I achieved to write is below:
$this->db->pages->find(array( 'skilltag' => 'Bilardo'), array('posts.index' => 1))->sort( array("posts.index" => -1));
I'm not willing to use "index" fields and also "currentIndex" field. But I put them anyways in case of not being able to work on "date" field which has timestamp values.
The above code returns an array with only one element which is an array that holds 2 elements:
{
"postId": {
"$oid": "52e12e5933a9fbec1100002d"
},
"date": 1390489177.267876,
"index": 1
},
{
"postId": {
"$oid": "52e12e5f33a9fb141800002c"
},
"date": 1390489183.277084,
"index": 2
}
Isn't there an aggregation function which does filtering on inside the array? I could not find any aggregation that returns the minimum value. I only found aggregation to return values between min and max values which must be given by the user -- which does not work in my case.
Are the embedded objects in your posts array field always ordered by their date and index, ascending? Based on your schema, I would assume that new posts are added to the document via the $push update operator.
If the element to remove is always at the front of the array, you could very easily use $pop to remove it.
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.