Current Code:
$doc = array('ooxx' => array(1,2,3,4,5));
datamodel()->insert($doc);
$doc2 = array('ooxx' => array(6,7,8,9));
datamodel()->insert($doc2);
$macher = array('ooxx'=>array('$exists' => true), 'ooxx' => array('$nin'=>array(6)));
$res = datamodel()->findOne($macher);
print_r($res);
When I replace the $macher with bellow, it does work well, why? is this a bug of mongodb?
$macher = array( 'ooxx' => array('$nin'=>array(6)), 'ooxx'=>array('$exists' => true));
It doesn't work because the keys have the same name and one overwrites the other. So the "keys" need to be unique.
If you have two conditions for the same key you use the $and operator which takes an array of arguments:
$matcher = array(
'$and' => array(
array( 'ooxx' => array( '$nin' => array(6) ) ),
array( 'ooxx' => array( '$exists' => true ) )
)
)
Or for the JSON minded:
{
"$and": [
{ "ooxx": { "$nin": [6] } },
{ "ooxx": { "$exists": true } }
]
}
Which is a valid structure where what you are writing is not.
Related
How to modify an array based on the value as key?
array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
I tried the following but it's not working:
foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
My desired array:
array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
I'm stuck here for hours ... Please help
IF the "name" is irrelevant, I think also the previous answer should be fine.
If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.
My code is:
$a = array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 1234
)
);
print_r($a);
echo "\n================================\n\n";
$newArr = [];
foreach ($a as $k => $vArr) {
// maybe some validation would be useful here, check if they keys exist
$newArr[$vArr['cutoff']][] = $vArr['totals'];
}
print_r($newArr);
function changeArr($data){
$new = [];
foreach ($data as $v){
$new[$v['cutoff']][] = $v['totals'];
}
return $new;
}
I need to perform iterated explosions on values in one column of my two dimensional array, then re-group the data to flip the relational presentation from "tag name -> video id" to "video id -> tag name".
Here is my input array:
$allTags = [
[
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-THREE",
"video" => "64111",
]
];
I want to isolate unique video ids and consolidate all tag names (as comma-separayed values) that relate to each video id.
Expected output:
$allTagsResult = [
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64070",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64076",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64110",
],
[
"name" => "TAG-ONE,TAG-TWO,TAG-THREE",
"video" => "64111",
],
];
Somehow I did it by checking the value using nested loops but I wish to know if you guys can suggest any shortest method to get the expected output.
If you want to completely remove foreach() loops, then using array_map(), array_walk_recursive(), array_fill_keys() etc. can do the job. Although I think that a more straightforward answer using foreach() would probably be faster, but anyway...
$out1 = array_map(function ($data) {
return array_fill_keys(explode(",", $data['video']), $data['name']); },
$allTags);
$out2 = [];
array_walk_recursive( $out1, function ( $data, $key ) use (&$out2) {
if ( isset($out2[$key])) {
$out2[$key]['name'] .= ",".$data;
}
else {
$out2[$key] = [ 'name' => $data, 'video' => $key ];
}
} );
print_r($out2);
will give...
Array
(
[64070] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64070
)
[64076] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64076
)
[64110] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64110
)
[64111] => Array
(
[name] => TAG-ONE,TAG-TWO,TAG-THREE
[video] => 64111
)
)
if you want to remove the keys, then
print_r(array_values($out2));
The code could be compressed by piling all of the code onto single lines, but readability is more useful sometimes.
Another method if you don't like looping:
$video_ids = array_flip(array_unique(explode(",",implode(",",array_column($allTags,'video')))));
$result = array_map(function($id){
return ['name' => '','video' => $id];
},array_flip($video_ids));
array_walk($allTags,function($tag_data) use (&$result,&$video_ids){
$ids = explode(",",$tag_data['video']);
foreach($ids as $id) $result[$video_ids[$id]]['name'] = empty($result[$video_ids[$id]]['name']) ? $tag_data['name'] : $result[$video_ids[$id]]['name'] . "," . $tag_data['name'];
});
Demo: https://3v4l.org/vlIks
Below is one way of doing it.
$allTags = [
'0' => [
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
'1' => [
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
'2' => [
"name" => "TAG-THREE",
"video" => "64111",
]
];
$allTagsResult = array();
$format = array();
foreach( $allTags as $a ) {
$name = $a['name'];
$videos = explode(',', $a['video']);
foreach( $videos as $v ) {
if( !isset( $format[$v]) ) {
$format[$v] = array();
}
$format[$v][] = $name;
}
}
foreach( $format as $video => $names) {
$allTagsResult[] = array('name' => implode(',', $names), 'video' => $video);
}
echo '<pre>';
print_r($allTagsResult);
die;
You can check Demo
I am typically in favor of functional style coding, but for this task I feel it only serves to make the script harder to read and maintain.
Use nested loops and explode the video strings, then group by those video ids and concatenate name strings within each group. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($allTags as $tags) {
foreach (explode(',', $tags['video']) as $id) {
if (!isset($result[$id])) {
$result[$id] = ['video' => $id, 'name' => $tags['name']];
} else {
$result[$id]['name'] .= ",{$tags['name']}";
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'video' => '64070',
'name' => 'TAG-ONE,TAG-TWO',
),
1 =>
array (
'video' => '64076',
'name' => 'TAG-ONE,TAG-TWO',
),
2 =>
array (
'video' => '64110',
'name' => 'TAG-ONE,TAG-TWO',
),
3 =>
array (
'video' => '64111',
'name' => 'TAG-ONE,TAG-TWO,TAG-THREE',
),
)
I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];
I'm trying to call methods while building an array. I am building a fairly large config array which contains many re usable blocks.
This is the array that I'd like to get:
array(
"masterKey" => array(
"myKey" => array(
"valueField" => "hi"
),
"anotherKey" => array(
"valueField" => "hi again"
)
....
)
);
This is how I'd like to generate it:
array(
"masterKey" => array(
self::getValueField("myKey", "hi"),
self::getValueField("anotherKey", "hi again"),
...
)
);
private static function getValueField($key, $value)
{
return array($key =>
"valueField" => $value
);
}
But this gives me
array(
"masterKey" => array(
[0] => array(
"myKey" => array(
"valueField" => "hi"
)
),
[1] => array(
"anotherKey" => array(
"valueField => "hi again"
)
)
)
);
Instead of constructing the "masterKey" field as a literal, merge the arrays returned by self::getValueField:
array(
"masterKey" => array_merge(
self::getValueField("myKey", "hi"),
self::getValueField("anotherKey", "hi again"),
...
)
);
Just want to add that, for #giaour answer to work, code for the getValueField function should be:
<?php
private static function getValueField($key, $value)
{
return array(
$key => array(
"valueField" => $value
)
);
}
I have a table with some user email address like:
johndoe#somemail.com
test#test_mail.com
test2#test_mail.com
admin#company_mail.com
janedoe#someothermail.com
sales#company_mail.com
mruser#validmail.com
I want to get the user list with emails not ending with #test_mail.com OR #company_mail.com.
I succeeded this with following mongo query:
db.users.find({
userEmail: {
$nin: [/#test_mail.com$/,/#company_mail.com$/]
}
})
I trid to run the same query in PHP with following code but couldn't make it work:
$criteria = array(
"userEmail" => array(
'$nin' => array(
'$regex' => new \MongoRegex("/#test_mail.com|#company_mail.com/i")
)
)
);
$cursor = $collection->find($criteria);
Any suggestions?
The correct way to apply this is with a singular MongoRegex object and the $not operator to reverse the condition:
$cursor = $users->find(array(
"userEmail" => array(
'$not' => new MongoRegex('/\#test_mail\.com$|\#company_mail\.com$/i')
)
));
foreach ( $cursor as $doc ) {
var_dump( $doc );
}
The same applies to $nin where you can actually specify a "regex" argument, but it must be an regular expression "object" type and not the operator form:
$cursor = $user->find(array(
"userEmail" => array(
'$nin' => array(new MongoRegex('/\#test_mail\.com$|\#company_mail\.com$/i'))
)
));
foreach ( $cursor as $doc ) {
var_dump( $doc );
}
But not really necessary as you are not providing an "array" of different values, the regular expression can represent the "or" condition itself.
You shouldn't use $nin in this case, I would try something like this:
$criteria = array(
"userEmail" => array(
'$not' => array(
'$or' => array(
'$regex' => new \MongoRegex("/#test_mail\.com$/i"),
'$regex' => new \MongoRegex("/#company_mail\.com$/i"),
),
),
)
);
UPD:
you can try this:
$criteria = array(
'$not' => array(
'$or' => array(
"userEmail" => array('$regex' => new \MongoRegex("/#test_mail\.com$/i")),
"userEmail" => array('$regex' => new \MongoRegex("/#company_mail\.com$/i")),
),
),
)
);