edit array in mongodb - PHP - php

My data like this:
Array
(
[_id] => MongoId Object
(
[$id] => 51a6fca3f348aca011000000
)
[first_name] => Phan
[last_name] => Chuong
[interests] => Array
(
[0] => football
[1] => swimming
[2] => PHP
[3] => music
)
)
I want edit value PHP to PHP1 or set PHP to null. Please help me how can i do it? Thanks all!

You could use the MongoCollection::update() method like this:
// $c is your MongoCollection Object
$updatedata = array('$set' => array("interests.2" => "PHP1"));
$id = new MongoID('51a6fca3f348aca011000000')
$c->update(array("_id" => $id), $updatedata);
The update method needs two arrays, the first one will tell the DB which Object to update ( In this example where id = our id, always use the MongoID Object, always!), the second array defines what to update, note that you can get to values in nested arrays wit the dot like above. $set is an Field Update Operator, read more on them here:
http://docs.mongodb.org/manual/reference/operator/update-field/
Or you could just get the entire Array, change it, and save it back.
$cursor = $c findOne("_id",4cb30f560107ae9813000000);
$cursor['interests'][2] = 'whatever';
$c->update($cursor);

Related

Extract data from php array

I have the following array in my Moodle plugin:
Array (
[0] => stdClass Object (
[id] => 32
[sessionid] => 5
[sessiontimezone] => CET
[timestart] => 1464071400
[timefinish] => 1464102000 )
[1] => stdClass Object (
[id] => 33
[sessionid] => 5
[sessiontimezone] => CET
[timestart] => 1465281000
[timefinish] => 1465311600 )
)
How to get the data. Right now, when I make:
$pluginsessiondates = $DB->get_record('plugin_sessions', array('id'=>$sessionid));
I get only data from the frist array [0]
How to get the data from every array key and then the single values? Thanks in advance.
The Moodle DB functions are for getting data out of the database, rather than from an array somewhere inside your plugin.
If you have an array somewhere, then you can get fields from it by writing:
echo $myarray[0]->id;
echo $myarray[1]->id;
etc.
If you are not trying to get data out of an existing array and want, instead, to get it out of the database, then $DB->get_record() will, as its name implies, get you only a single record, whereas $DB->get_records() will get you all the matching records:
$sessions = $DB->get_records('plugin_sessions', array('sessionid' => $sessionid));
foreach ($sessions as $session) {
echo $session->id;
}

PDO fetchAll() primary key as array group key

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).
My current code:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
Which then outputs:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.
Is it possible for me to group each array by their primary key (which is id)?
You can just use
$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))
PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.
This should yield what you are looking for :
$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:
$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
$Array[$d['id']]["id"] = $d['id'];
$Array[$d['id']]["name"] = $d['name'];
$Array[$d['id']]["path"] = $d['path'];
}
// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) )
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.
I'd like to point out the only solution that works for me:
fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
Beware that this will strip the first column from the resultset. So the query must be:
SELECT id_keyname AS arrkey, id_keyname, .... FROM ...
I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.
The code(in human readable form) will be:
$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) {
$temp2 = $temp['id'];
unset($temp['id']);
$returnArray[$temp2] = $temp;
return $returnArray;
}
);
So, my question is; is it possible for me to group each array by their
primary key (which is id)
Off course, you have 2 options here: Either to change the query or parse a result-set.
So, I'm sure you don't want to change query itself, so I'd go with parsing result-set.
Note:
You should use prepared SQL statements when they make sense. If you want to bind some parameters then its OKAY. But in this case, you only want get get result-set, so prepare() and fetch() will be kinda overdo.
So, you have:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
And you want:
Array( [id] => Array('bar' => 'foo') ....)
Well, you can do something like this:
$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();
foreach($stmt as $array){
$result[$array['id']] = $array;
}
print_r($result); // Outputs: Array(Array('id' => Array(...)))

How to get data from array in object

I can't seem to get specific data from an array inside an object.
$this->fields->adres gets the address correctly, but i can't get a level deeper.
I've tried:
$this->fields->province
$this->fields->province->0
$this->fields->province[0]
And: (edit)
$this->fields["province"][0]
$this->fields['province'][0]
$this->data->fields['province'][0]
But it does not return anything while it should return "Flevoland".
First part of the object print_r($this, TRUE) below:
RSMembershipModelSubscribe Object
(
[_id] => 2
[_extras] => Array
(
)
[_data] => stdClass Object
(
[username] => testzz
[name] => testzz
[email] => xxxx#example.com
[fields] => Array
(
[province] => Array
(
[0] => Flevoland
)
[plaats] => tesdt
[adres] => test
You can also use type casting.
$fields = (array) $this->data->fields;
echo $fields['province'][0];
As you can see by your output, object members are likely to be private (if you follow conventions, anyway you must prepend an underscore while calling them), so you're calling them the wrong way;
This code works:
$this->_data->fields['province'][0];
You can see it in action here;
I created a similar object, and using
$membership = new RSMembershipModelSubscribe();
echo $membership->_data->fields['province'][0];
outputs "Flevoland" as expected.
As fields is already an array, try this:
$this->fields['province'][0]
This assuming the [_data] object is $this.
Fields and province are both arrays, you should be trying $this->fields["province"][0]
$this->_data->fields['province'][0]

How to access stdclass object after a specific key value pair?

I have a stdclass object as shown below:
stdClass Object
(
[text] => Parent
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Laurence W. Lane Jr.
[url] => http://www.freebase.com/view/m/0c02911
)
)
)
I iterate over multiple such objects, some of which have
stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
I was wondering how I would access the "values" object if it comes after a "text" that has "Parent" as its value?
there are serveral ways to turn it to array:
First Solution:
$value = get_object_vars($object);
Second Solution:
$value = (array) $object;
Third Solution
$value = json_decode(json_encode($object), true);
to get value of converted array
echo $value['values']['0']['id'];
The alternate way to access objects var without convert the object, try
$object->values->{'0'}->id
Expanding (or rather minimalizing) upon answer by Somwang Souksavatd, I like accessing Object values like this:
echo get_object_vars($object)['values']['0']['id'];
I had the same issue, still not so sure why but I was able to get it working using this workaround:
$k2 ="1";
$elements = json_decode('{"id":"1","name":"User1"}');
//$elements['id'] == $k2; //****Not Working
$tmp = (object)$elements;
$tmp = $tmp ->id; //****Working
//$tmp =$elements['id'] ; //****Not Working
return $tmp == $k2;
I have to say that sometimes accessing the element as array works and some times not,(On PHP7 it worked for me but on PHP5.6 it didn't).
$elements can be Array to but I chose to demonstrate with json string.
I hope this helps somehow !!!
$Obj=stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
$Values= $result->values;
$Item = $Values[0];
$id=$Item->id;
$text = $Item->text;
$url=$Item->url;
I'm doing the same thing and all I did was this;
<?php
$stdObject = json_decode($stdClassObject);
print $stdObject->values[0]->id;
this can help you accessing subarrays in php using codeigniter framework
foreach ($cassule['tarefa'][0] as $tarefa => $novo_puto_ultimos_30_dias) {
echo $novo_puto_ultimos_30_dias;
What you are looking for is the Object['values'][0]: 'values' is the keymap just like 'text', and [0] is the index inside that array you wish to access. so if you would like to get the id deep in the nest, you'd have to do something like
Object['values'][0]['id']
or
Object['values'][0]->id
which should give you /m/0c02911. But I have no idea how you are doing your loop, so you will have to adjust it to your needs and place proper variables where they need to go in that code in your loop. Not exactly sure which language you are working with.

Find documents based on referenced ID in MongoDB & PHP

i've got referenced Users collection object in my MongoDB Items collection. Random Item document looks like this:
ps: to clarify, i really dont want to embed Items into Users collection.
Array
(
[_id] => MongoId Object
(
[$id] => 4d3c589378be56a008000000
)
[modified] => 1295800467
[order] => 1
[title] => MyFirstItem
[user] => Array
(
[$ref] => users
[$id] => MongoId Object
(
[$id] => 4d3c55e7a130717c09000012
)
)
)
So i need to find only items, which are assigned to the specific user. Find this question of my problem, but the solution didnt work for me.
MongoDB-PHP: JOIN-like query
Here is snippet of my code, givin' me no results at all.
$user = $db->users->findOne(array("_id" => new MongoID("4d3c55e7a130717c09000012")));
$items = $db->items->find(array("user" => array('$id' => $user["_id"])));
What is the correct way to finding that data? Should i instead put an user_id as a MongoID without reference?
Spent all my day with this, thanks in advance!
Try
$items = $db->items->find(array("user.$id" => $user["_id"]));

Categories