Consider an Array
$lettersArray = [A,C,E,G]
and my MongoDB Collection has the following structure.
{
Collection : {
letters:{
A:{...},
B:{...},
...
Z:{...}
}
}
}
Consider that the Letter Sub document is a part of a larger collection. Hence I am using Aggregation.
Right Now I have tried to project -
['$Collection.letters' => ['$elemMatch' => ['$in' => $lettersArray]]
and also tried
['Letters' => ['$in' => [$lettersArray,'$Collection.letters']]
But it didn't work.
In the End, I want result like the following:
[
Collection => [
letters => [
A => [...],
C => [...],
E => [...],
G => [...]
]
]
]
Is there any way to do this?
In PHP you can use array_combine with array_fill to create the empty arrays.
$lettersArray = ['A','C','E','G'];
$letters = array_combine($lettersArray, array_fill(0,count($lettersArray), []));
Array_fill creates an array from index 0, to the count of items in $lettersArray with the contents []
Output:
array(4) {
["A"]=>
array(0) {
}
["C"]=>
array(0) {
}
["E"]=>
array(0) {
}
["G"]=>
array(0) {
}
}
https://3v4l.org/TeoFv
I think you are mistaken in the way you are trying to access the documents' information.
If you take a look at your MongoDB document, you will see that it is in fact not an array, so you should not use $elemMatch to project these fields, but simple projections. In your case, you should project in this way:
[
'$project' => [
'Collection.letters.A' => 1,
'Collection.letters.C' => 1,
'Collection.letters.E' => 1,
'Collection.letters.G' => 1
]
]
By the way, you don't need to use the aggregation framework to compute such a projection. You could just use find(), and use the projection in the options, which are the functions' second argument:
myCollection->find(query, [
'projection' => [
'Collection.letters.A' => 1,
'Collection.letters.C' => 1,
'Collection.letters.E' => 1,
'Collection.letters.G' => 1
]
]);
Cheers,
Charles
Related
I have multidimensional array like this:
$obj = array(
"a" => array(
"aa" => array(
"aaa" => 1
),
"bb" => 2,
),
"b" => array(
"ba" => 3,
"bb" => 4,
),
"c" => array(
"ca" => 5,
"cb" => 6,
),
);
I can not figured out a neatest way, e.g. custom-depth function, to extract item at specific location with arguments to function (or array of key names). For example:
echo $obj[someFunc("a", "aa", "aaa")];
... should return 1.
print_r($obj[someFunc("a")]);
... should return:
Array
(
[aa] => Array
(
[aaa] => 1
)
[bb] => 2
)
What is the best way to accomplished this with php7 features?
Since PHP 5.6, ["Variadic functions"][1] have existed. These provide us with a nice simple to read way to collect arguments used in calling a function into a single array. For example:
function getValue(...$parts) {
var_dump($parts);
}
getValue('test', 'part');
Will output:
array(2) {
[0]=>
string(4) "test"
[1]=>
string(4) "part"
}
This was all possible before using built-in functions to get the parameters, but this is more readable.
You could also be a little more explicit with the argument types, but I'll leave that for you to figure out if necessary.
You next major challenge is to loop through the arguments. Something like this will produce the value that you desire.
function getValue(...$parts) {
$returnValue = $obj;
foreach ($parts as $part) {
$returnValue = $obj[$part];
}
return $returnValue;
}
However, this is rather crude code and will error when you try calling it to access non-existent parts. Have a play and fix those bits.
[1]: https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
I've got simple array of objects:
"myObject" => [
'key1' => ["property1" => 'value1', "property2" => 'value2'],
'key2' => ["property1" => 'value1', "property2" => 'value2'],
...
],
When I'm returning this via laravel dot syntax:
return [
'listOfObjects' => trans(objects)
]
I've got:
myObject: {
key1: {property1:'value1', property2:'value2'},
key2: {property1:'value1', property2:'value2'},
etc..
}
It's simple.
Now how can I modify my return to get only an array of objects, without numbers:
myObject: {
{property1:'value1', property2:'value2'},
{property1:'value1', property2:'value2'},
etc..
}
Any ideas?
I don't think it is possible to solve in PHP. As it is said in the manual
"...index may be of type string or integer. When index is omitted, an
integer index is automatically generated, starting at 0..."
Also, what you are asking seems to be quite pointless. If you could describe what it is you are trying to accomplish, people might be able to help you better.
The function to use in this case is:
$tryit = trans('objects');
$new = collect($tryit)->flatten(1);
$new->values()->all();
unfortunatelly there is a bug in Laravel 5.6 on this function and it digs two level deep instead of one :/
[edit]
I think I now understand what you want. What you call an Array in PHP is not necessarily an Array in JSON. For JSON your "myObject" is an Object.
For JSON to recognize something as an Array, it can only have numbers as keys.
So change the keys from "key1", "key2", ... into 0, 1, ...
$result = [];
foreach($myObject as $element){
$result[] = $element;
}
return $result;
After that, $result looks like this
$result = [
0 => ["prop1" => "val1", "prop2" => "val2"],
1 => ["prop1" => "val1", "prop2" => "val2"]
]
Or equivalently in the short notation
$result = [
["prop1" => "val1", "prop2" => "val2"],
["prop1" => "val1", "prop2" => "val2"]
]
Now JSON should recognize this as an Array instead of an Object when Laravel converts $result to JSON or you make it yourself: return response()->json($result);
[previous:]
You can not return an object which has values but no keys.
The simplest form of keys are numbers, which is what arrays are using.
I recently found a bug in my application caused by unexpected behaviour of array_merge_recursive. Let's take a look at this simple example:
$array1 = [
1 => [
1 => 100,
2 => 200,
],
2 => [
3 => 1000,
],
3 => [
1 => 500
]
];
$array2 = [
3 => [
1 => 500
]
];
array_merge_recursive($array1, $array2);
//returns: array:4 [ 0 => //...
I expected to get an array with 3 elements: keys 1, 2, and 3. However, the function returns an array with keys 0, 1, 2 and 3. So 4 elements, while I expected only 3. When I replace the numbers by their alphabetical equivalents (a, b, c) it returns an array with only 3 elements: a, b and c.
$array1 = [
'a' => [
1 => 100,
2 => 200,
],
'b' => [
3 => 1000,
],
'c' => [
1 => 500
]
];
$array2 = [
'c' => [
1 => 500
]
];
array_merge_recursive($array1, $array2);
//returns: array:3 [ 'a' => //...
This is (to me at least) unexpected behaviour, but at least it's documented:
http://php.net/manual/en/function.array-merge-recursive.php
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
The documentation isn't very clear about what 'appended' means. It turns out that elements of $array1 with a numeric key will be treated as indexed elements, so they'll lose there current key: the returned array starts with 0. This will lead to strange outcome when using both numeric and string keys in an array, but let's not blame PHP if you're using a bad practice like that. In my case, the problem was solved by using array_replace_recursive instead, which did the expected trick. ('replace' in that function means replace if exist, append otherwise; naming functions is hard!)
Question 1: recursive or not?
But that's not were this question ends. I thought array_*_resursive would be a recursive function:
Recursion is a kind of function call in which a function calls itself.
Such functions are also called recursive functions. Structural
recursion is a method of problem solving where the solution to a
problem depends on solutions to smaller instances of the same problem.
It turns out it isn't. While $array1 and $array2 are associative arrays, both $array1['c'] and $array2['c'] from the example above are indexed arrays with one element: [1 => 500]. Let's merge them:
array_merge_recursive($array1['c'], $array2['c']);
//output: array:2 [0 => 500, 1 => 500]
This is expected output, because both arrays have a numeric key (1), so the second will be appended to the first. The new array starts with key 0. But let's get back to the very first example:
array_merge_recursive($array1, $array2);
// output:
// array:3 [
// "a" => array:2 [
// 1 => 100
// 2 => 200
// ]
// "b" => array:1 [
// 3 => 1000
// ]
// "c" => array:2 [
// 1 => 500 //<-- why not 0 => 500?
// 2 => 500
// ]
//]
$array2['c'][1] is appended to $array1['c'] but it has keys 1 and 2. Not 0 and 1 in the previous example. The main array and it's sub-arrays are treated differently when handling integer keys.
Question 2: String or integer key makes a big difference.
While writing this question, I found something else. It's getting more confusing when replacing the numeric key with a string key in a sub-array:
$array1 = [
'c' => [
'a' => 500
]
];
$array2 = [
'c' => [
'a' => 500
]
];
array_merge_recursive($array1, $array2);
// output:
// array:1 [
// "c" => array:1 [
// "a" => array:2 [
// 0 => 500
// 1 => 500
// ]
// ]
//]
So using a string key will cast (int) 500 into array(500), while using a integer key won't.
Can someone explain this behaviour?
If we take a step back and observe how array_merge*() functions behave with only one array then we get a glimpse into how it treats associative and indexed arrays differently:
$array1 = [
'k' => [
1 => 100,
2 => 200,
],
2 => [
3 => 1000,
],
'f' => 'gf',
3 => [
1 => 500
],
'99' => 'hi',
5 => 'g'
];
var_dump( array_merge_recursive( $array1 ) );
Output:
array(6) {
["k"]=>
array(2) {
[1]=>
int(100)
[2]=>
int(200)
}
[0]=>
array(1) {
[3]=>
int(1000)
}
["f"]=>
string(2) "gf"
[1]=>
array(1) {
[1]=>
int(500)
}
[2]=>
string(2) "hi"
[3]=>
string(1) "g"
}
As you can see, it took all numeric keys and ignored their actual value and gave them back to you in the sequence in which they were encountered. I would imagine that the function does this on purpose to maintain sanity (or efficiency) within the underlying C code.
Back to your two array example, it took the values of $array1, ordered them, and then appended $array2.
Whether or not this behavior is sane is a totally separate discussion...
You should read the link you provided it states (emphasis mine):
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
Hi I have an array that contains two arrays that has the following structure:
categories [
"lvl0" => array:2 [
0 => "Cleaning"
1 => "Bread"
]
"lvl1" => array:2 [
0 => null
1 => "Bread > rolls"
]
]
I would like to remove any records of NULL from the 'lvl1' array but have not been able to find the correct method to do this.
I have tried:
array_filter($categories['lvl1'])
But this also removes all records associated to lvl1 and not just the NULL ones.
Any help would be greatly appreciated.
Thanks
array_filter() takes a callback as the second argument. If you don't provide it, it returns only records that aren't equal to boolean false. You can provide a simple callback that removes empty values.
array_filter() also uses a copy of your array (rather than a reference), so you need to use the return value.
For instance:
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$lvl1 = array_filter($categories['lvl1'], function($value) {
return !empty($value);
});
var_dump($lvl1);
That will return:
array(1) {
[1] =>
string(13) "Bread > rolls"
}
I was having the same issue on my last working day.Generally for associative array array_filter() needs the array key to filter out null, false etc values. But this small function help me to filter out NULL values without knowing the associative array key. Hope this will also help you, https://eval.in/881229
Code:
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$result = array_filter_recursive($categories);
print '<pre>';
print_r($result);
print '</pre>';
Output:
(
[lvl0] => Array
(
[0] => Cleaning
[1] => Bread
)
[lvl1] => Array
(
[1] => Bread > rolls
)
)
Ref: http://php.net/manual/en/function.array-filter.php#87581
Robbie Averill who commented on my post with the following solved the issue:
$categories['lvl1'] = array_filter($categories['lvl1']);
I'm fairly new to Mongo and PHP. I've been fine with the relatively simple stuff but I've hit a snag performing a php find within a mongo collection conditionally limited by an array of _id's.
Here's a walkthrough...
// "characters" collection
{ "_id":{"$id":"3f177b70df1e69fe5c000001"}, "firstname":"Bugs", "lastname":"Bunny" }
{ "_id":{"$id":"3f2872eb43ca8d4704000002"}, "firstname":"Elmer", "lastname":"Fudd" }
{ "_id":{"$id":"3f287bb543ca8de106000003"}, "firstname":"Daffy", "lastname":"Duck" }
// "items" collection
{ "_id":{"$id":"4f177b70df1e69fe5c000001"}, "mdl":"carrot", "mfg":"Wild Hare Farms ltd.", "ownerid":{"$id":"3f177b70df1e69fe5c000001"} }
{ "_id":{"$id":"4f2872eb43ca8d4704000002"}, "mdl":"hat", "mfg":"Acme Inc.", "ownerid":{"$id":"3f2872eb43ca8d4704000002"} }
{ "_id":{"$id":"4f287bb543ca8de106000003"}, "mdl":"spaceship", "mfg":"Acme Inc.", "ownerid":{"$id":"3f287bb543ca8de106000003"} }
// Let's say I do a find on the item collection for a specific manufacturer...
$itemOwners = $db->items->find(array("mfg" => "Acme Inc."), array("ownerid"));
// The result looks something like this...
[
"4f2872eb43ca8d4704000002":{"_id":{"$id":"4f2872eb43ca8d4704000002"},"ownerid":{"$id":"3f2872eb43ca8d4704000002"}},
"4f287bb543ca8de106000003":{"_id":{"$id":"4f287bb543ca8de106000003"},"ownerid":{"$id":"3f287bb543ca8de106000003"}}
]
// I'd now like to perform a find on the character collection and get the corresponding owner documents.
// To do that I need to build the $in array from the previous find results...
foreach ($itemOwners as $doc)
$itemOwnersTemp[] = $doc["ownerid"];
$itemOwners = $itemOwnersTemp;
// The resulting array looks like this. I've read that the ids need to be in MongoId format. Seems like they are?
[
{"$id":"3f2872eb43ca8d4704000002"},
{"$id":"3f287bb543ca8de106000003"}
]
// and (finally) the conditional find. The result set is always empty. What am I tripping up on?
$characterDocs = $db->characters->find(array("_id" => array('$in' => $itemOwners));
I've just tried this with slightly modified code:
<?php
$m = new Mongo('localhost:13000', array( 'replicaSet' => 'a' ) );
$db = $m->demo;
$db->authenticate('derick', 'xxx');
// "characters" collection
$c = $db->characters;
$c->insert(array( '_id' => new MongoID("3f177b70df1e69fe5c000001"), 'firstname' => 'Bugs', 'lastname' => 'Bunny' ));
$c->insert(array( '_id' => new MongoID("3f2872eb43ca8d4704000002"), 'firstname' => 'Elmer', 'lastname' => 'Fudd' ));
$c->insert(array( '_id' => new MongoID("3f287bb543ca8de106000003"), 'firstname' => 'Daffy', 'lastname' => 'Duck' ));
// "items" collection
$c = $db->items;
$c->insert(array( '_id' => new MongoId("4f177b70df1e69fe5c000001"), 'mdl' => 'carrot', 'ownerid' => new MongoID('3f177b70df1e69fe5c000001')));
$c->insert(array( '_id' => new MongoId("4f2872eb43ca8d4704000002"), 'mdl' => 'hat', 'ownerid' => new MongoID('3f2872eb43ca8d4704000002')));
$c->insert(array( '_id' => new MongoId("4f287bb543ca8de106000003"), 'mdl' => 'space', 'ownerid' => new MongoID('3f287bb543ca8de106000003')));
// Let's say I do a find on the item collection for a specific manufacturer...
$itemOwners = $db->items->find(array("mdl" => "hat"), array("ownerid"));
// The result looks something like this...
/*[
"4f2872eb43ca8d4704000002":{"_id":{"$id":"4f2872eb43ca8d4704000002"},"ownerid":{"$id":"3f2872eb43ca8d4704000002"}},
"4f287bb543ca8de106000003":{"_id":{"$id":"4f287bb543ca8de106000003"},"ownerid":{"$id":"3f287bb543ca8de106000003"}}
]*/
// I'd now like to perform a find on the character collection and get the corresponding owner documents.
// To do that I need to build the $in array from the previous find results...
foreach ($itemOwners as $doc) {
$itemOwnersTemp[] = $doc["ownerid"];
}
$itemOwners = $itemOwnersTemp;
// The resulting array looks like this. I've read that the ids need to be in MongoId format. Seems like they are?
/*
[
{"$id":"3f2872eb43ca8d4704000002"},
{"$id":"3f287bb543ca8de106000003"}
]
*/
// and (finally) the conditional find. The result set is always empty. What am I tripping up on?
$characterDocs = $db->characters->find(array("_id" => array('$in' => $itemOwners)));
var_dump( iterator_to_array( $characterDocs ) );
?>
And it provides the output that I expect:
array(1) {
["3f2872eb43ca8d4704000002"]=>
array(3) {
["_id"]=>
object(MongoId)#3 (1) {
["$id"]=>
string(24) "3f2872eb43ca8d4704000002"
}
["firstname"]=>
string(5) "Elmer"
["lastname"]=>
string(4) "Fudd"
}
}
Somewhere, I think you're doing a wrong conversion but it's difficult to tell as you don't show the output of PHP.
Instead of this:
$itemOwnersTemp[] = $doc["ownerid"];
Try this:
$itemOwnersTemp[] = new MongoID($doc["ownerid"]);