I have a MongoDB object of following structure:
{
"_id": ObjectId("4f5ed7d33c9059a00d000002"),
"data":
{
"0": "data1",
"1": "data2",
"2": "data3",
"3": "data4",
}
}
I am using the following code to retrieve sliced result:
$obj1 = $collection->findOne(array('_id' => new MongoId('4f5ed7d33c9059a00d000002')),array('_id'=>1,'data'=>array('$slice' =>2 )));
But the result of this query does not retain array indexes of array data.
You can use the $slice operator to retrieve a subrange of elements in an array.
What you are trying to slice is a document (subdocument). Arrays use fixed positions for the elements, [0..(numelements-1)] so there's no way to keep the "indexes". Unfortunately php's equivalent of a document is an associative array hence the confusion.
Related
Is there a way in PHP Mongodb to write an object in an already existing document and only overwrite or add the values contained in the object.
The object structure is not known to me.
Here is a sample:
existing document:
{
"package": {
"parameter": "value",
"one": "two"
}
}
php object or array:
$obj[package][parameter] = "value2"
$obj[package][new] = "test"`
result schould be
{
"package": {
"parameter": "value2",
"one": "two",
"new": "test"
}
}
I need something like array_merge()
I tried the $merge aggerator but it does not seem to work.
Unknown modifier: $merge. Expected a valid update modifier or pipeline-style update specified as an array
$merge is used to insert/update document to collection, like the UPSERT command in SQL. Have a look at $mergeObjects. Use it in combination with $replaceWith (or $replaceRoot which is just an alias)
Would be something like
{ $replaceWith: { $mergeObjects: [ "$$ROOT", {"new" : "test"} ] } }
$$ROOT is the existing object. If the existing object has any fields with the same name as your new object, then it will be overwritten with new field values. If you like to prefer the existing fields, then flip the arguments in the array.
The sample data you provided is not valid JSON, thus I cannot provide a full solution.
I have this kind of array object
$data = [
1 => {
"id": 1
"time_in": "08:00:00"
"time_out": "17:00:00"
}
]
I want to change it to be like this
$data =[{
"id": 1
"time_in": "08:00:00"
"time_out": "17:00:00"
}]
I don't know how I shall do it, should I use loop for this or is their a function for it?
You can get the items from the collection first so that it will be an array. And then you can convert it any way you want. Try below.
$items = $data->all();
array_values($items)
The structure you're proposing to change it to is invalid, nor would it have any value over the structure you already have.
1 => {
...
Here 1 is your array key; you're not forced to do anything with it.
Perhaps you don't need an array at all, in which case simply drop the square brackets. The code example you posted suggests to me that you may also want to look at json_encode(): http://php.net/manual/en/function.json-encode.php
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 want to filter results from my array using php
my array 1
{
"id": 23,
"name": "nectarine",
"lactose": "Moderate"
},
{
"id": 27,
"name": "peach, white",
"lactose": "None"
},
this is my array 2
{
"0": "None",
"4": "Moderate"
}
i want to get None results and Moderate results seperatly from array 1,
this is my current set ,
how can i do this. pls advice
Create two new arrays: "none" and "moderate" and iterate through array1 and push the id of each into the respective new arrays based on the value associated with "lactose". This will give you two arrays with only the ids of those items in each category and you can then use that to identify the name of each using the original array. Not sure how array two figures into the story, but this will give you a way of separating the items of array1 based on the lactose content. I can post the code required if you are still stuck. but you should try doing it yourself to learn about array_push() and other php stuff.
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