Is there an equivalent to MySql's getLastInsertID() in MongoDb & PHP? - php

The title asks it all.
I have found an example that looked something like this:
db.find(fields = {"-id"}).sort("-id", -1).limit(X)
but that doesn't seem safe because that is assuming the ids will actually be in order.

$item = array( ... );
$mongo_collection->insert($item);
$id = $item['_id'];
It'll add the ID to the $item array. Also note you can use an object instead of an array if it's your preference.

Related

merging and then sorting 2 arrays in php & wordpress

I'm trying to merge 2 arrays in PHP and then sort them.
I'm pulling data from WordPress database ( tags and categories ) and I need to merge them and sort them properly.
Code looks similar to this:
$categories = [
'<a>WordPress Tips</a>',
'<a>SEO Tips'</a>,
'<a>Development Tips</a>'
];
$tags = [
'<a>WordPress</a>',
'<a>SEO'</a>,
'<a>Development</a>'
];
$taxonomies = array_merge($categories, $tags);
sort($taxonomies);
Since I need to loop through $taxonomies array and print them with anchors included ( every one of those must have a valid URL to itself ), I don't get a proper sorting result. However, as soon as I 'strip out' all the tags around these items, sorting works as it should, but I don't get URLs that I need, only string / text.
Could someone suggest a better sorting algorithm which would sort these items properly with html elements included around them? Thanks!
You need to do custom comaprision to make it work using usort() and strip_tags()
<?php
$taxonomies = array_merge($categories, $tags);
print_r($taxonomies);
function cmp($a, $b){
$data1 = strip_tags($a);
$data2 = strip_tags($b);
return ($data1 < $data2) ? -1 : 1;
}
usort($taxonomies, "cmp");
print_r($taxonomies);
Output:-https://eval.in/934071
Since you mentioned that the tags stripped version works, a simple way might be to use them as the keys in the sort. Something like this, for instance :
$taxonomies = array_merge( $categories, $tags );
$toSort = [];
foreach($taxonomies as $tax) {
$toSort[strip_tags($tax)] = $tax;
}
ksort( $toSort );
print_r( $toSort );
Which will give the sorted array and you can just use the values in there. Maybe there's better options but this comes to mind off the top of my head..
EDIT : uasort with a comparision function that actually compares the stripped versions might be better, after looking at other answers here.

Assigning a value to a variable?

I'm working on a PHP project and would love to get some help on variables.
I have a function that looks like this:
function custom_get_tour_nearest_booking_dates( $tour_id, $limit = 2, $exclude_booked_tickets = false ) {
$result = array();
if ( $tour_id < 1 ) {
return $result;
}
The database holds a set of products, each of these with a unique ID made up by numeric values, like 1233,2355,6532 and so on.
If I want to display the characteristics of one of these products, how do I link the ID to the variable $tour_id?
Somewhere you call that method: custom_get_tour_nearest_booking_dates(4);
Like the example above, 4 is the tour_id. Besides that, your method is kinda useless.

Sorting a collection in doctrine2

I've written the following query (that may or may not be efficient, I'm still a newbie):
$collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name');
$query = array('array_name' => new \MongoId(id));
$cursor = $collection->find($query)->limit(9)->sort('r', 'desc');
I'm trying to sort by an r value that looks like this in the document:
"r": 0.58325652219355106354
but it isn't actually sorting it by that r-value. What am I doing wrong?
Pretty sure sort takes an array argument. Try
->sort(['r' => 'desc]);
I looked it up...
http://apigen.juzna.cz/doc/doctrine/mongodb/source-class-Doctrine.MongoDB.Cursor.html#564-585

How to apply PHP function to a column returned from CakePHP query

In my controller I am retrieving records from my institutions table with the following fields
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture'),
);
$institutions = $this->Institution->find('all',$params);
How can I prefix each 'Institution.picture' field with the full URL address, 'Institution.picture' itself only holds the name of the file.
I would also like to perform html_entity_decode() on each 'Institution.about' value from the returned set.
I know how to do this only without the framework if I make custom queries from scratch, then I would iterate each row and apply PHP functions to the field of interest. But is there a place in CakePHP (find or paginator) that I can specify such PHP manipulation on each field value from the returned set?
NOTE: I don't like to do this in the View, as I want to output it as json directly
You can define a virtualField for model:
public $virtualFields = array('image_url' => "CONCAT('/img/', Institution.picture)");
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture',
'Institution.image_url'),
);
$institutions = $this->Institution->find('all',$params);
Unfortunaly MySQL doesn't have a function to decode HTML entities. You may utilize an afterFind() callback instead of virtualField. This lets you to decode entities as well as add a prefix.
CakePHP is php
Just iterate over the array and prepare it however you want:
$institutions = $this->Institution->find('all',$params);
$prefix = '/img/'; // <- define this
foreach ($institutions as &$row) {
$row['Institution']['about'] = html_entity_decode($row['Institution']['about']);
$row['Institution']['picture'] = $prefix . $row['Institution']['picture'];
}
If this is always required it can be applied to all finds via an afterFind method in the institution class.
I think you should do it in the View. See this example.
Hash::map can be very useful here. By specifying path you can only modify slices of the set.

use different string in function?

I am a total NOOB in programming (but this is only my second question on stackoverflow :-) ).
By a foreach function I get 5 different string values for $Loncoord, $Latcoord, $gui;
this I can see with the print_r in the code written below:
"-5.68166666667","+24.6513888889","IMG_3308",
But I now want to create 5 different markers in the $map->addMarkerByCoords (function is it ?).
print_r ("$Loncoord");
print_r ("$Latcoord");
print_r ("$gui");
$map->addMarkerByCoords("$Loncoord","$Latcoord","$gui",'OldChicago');
Is this possible?
Do I need to put them in a array and call these in the (function ?) or do I need to use a foreach function?
I tried both for a week now but I can't get it working.
Can you help me?
The answers you produced gave me a turn in the right direction.
Thank you for the quick responses and the explaining part.
But for the addMarkerByCoord (function! (stupid me)) I found this in the googlemaps API:
function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '') {
$_marker['lon'] = $lon;
$_marker['lat'] = $lat;
$_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
$_marker['title'] = $title;
$_marker['tooltip'] = $tooltip;
$this->_markers[] = $_marker;
$this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
// return index of marker
return count($this->_markers) - 1;
}
It depends on the implementation of map::addMarkerByCoords()
The method (not a function) name, and its signature, suggests that you are only able to add one coord at a time. But to be sure you'ld need to know the methods true signature. So the question is: does the method allow arrays as arguments?
Usually, a method that allows you to add multiple items at once, has the plural name of the intended action in it's name:
map::addMarkersByCoords() // note the s after Marker
If the 'map' class is your own implementation, you are free to implement it the way you like of course, but in that case keep the descriptive names of the methods in mind. So, add one marker:
map::addMarkerByCoords()
Add multiple markers at once:
map::addMarkersByCoords()
Typically you would implement the plural method as something like this:
public function addMarkersByCoords( array $markers )
{
foreach( $markers as $marker )
{
$this->addMarkerByCoord( $marker[ 'long' ], $marker[ 'lat' ], $marker[ 'img ' ], $marker[ 'name' ] );
}
}
Basically, the plural method accepts one array, and adds each individual marker by calling the singular method.
If you wanna get even more OOP, you could implement the plural and singular method to accept (an array of) Marker objects. But that is not particalarly relevant for this discussion.
Also, the suggested expantion of the Map's interface with a plural method doesn't nessecarily mean you can't add multiple markers outside the object with calling the singular method in a foreach loop. It's up to your preference really.
If you want to call the addMarkerByCoords for 5 times with 5 different values for each parameter then you can build an array for every parameter and then iterate with the foreach function:
$Loncoord=array(1,2,3,4,5);
$Latcoord=array(1,2,3,4,5);
$gui=array(1,2,3,4,5);
$city=array('OldChicago','bla','bla','bla','bla');
foreach($Loncoord as $k=>$v)
$map->addMarkerByCoords($Loncoord[$k],$Latcoord[$k],$gui[$k],$city[$k]);
Try losing some of the quotes...
$map->addMarkerByCoords($Loncoord,$Latcoord,$gui,'OldChicago');
To answer the question properly though, we would need to know what addMarkerByCoords was expecting you to pass to it.

Categories