This shows me everything (including 55d9d86746ba9a3a7f642b83).
I don't want it to show me the data in the array $veri.
$veri=Array
(
[0] => 55d9d86746ba9a3a7f642b83
)
$urun = $c->find(array('_id' => array('$nin' => $veri)));
Try the below code:
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("foo");
$cur = $db->bar;
$veri = array(
new MongoId('55d9d86746ba9a3a7f642b83')
);
$urun = $cur->find(array('_id' => array('$nin' => $veri)));
foreach($urun as $doc) {
var_dump($doc);
}
?>
Notice how I use MongoId, instead of just copy pasting the id as is. Also notice that the array doesn't need an index [0]
Related
So I have the following code to get a document from a collection in my database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document);
}
I'm able to successfully retrieve a document by searching for the username, so if $uname is "Jon", I get the following output:
stdClass Object ( [username] => Jon [email] => Jon#mail.com [passwd] => pass123 )
However, what I want to do is just return a single value from the document, so if I wanted to get the value for email, it would return:
Jon#mail.com
...so then I could store that value as a variable.
How would I do this?
Std class objects can be accessed via -> operator. So you can user $document->email to access individual email. Is this what you are looking for
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document->email);
}
I'm trying to write to a variable inside an object and I can't find how to do it.
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
I want to change person 8 to person 9
So I think that I need to get the rota_entry (using foreach) and then use Json_decode to get an array and then something but my brain now hurts :( I and don't know how to reset it back up to put into the database again.
I can find lots that talks about simple JSON decode or simple array parsing but not something to help with this
This code assumes $obj = the first entry in your array you show.
So $obj = Array[0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
This code changes rota_entry0 person 8 to 9
// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;
Try this:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
good luck.
I have code to get the address which is separated by space and then fetching area details about that address so each time sql result is stored in array "resultArray" and that result is pushed to another array "returnArray" which is then displayed in the format of json.I want to remove duplicate area_id in returnArray so I used "array_unique" but it's not working .Please give some suggestion.
Sample Code:
<?php
include_once 'main.php';
$dac = new Main();
$add = $_POST['address'];
$noLines = sizeof($add);
$resultArray=array();
$returnArray=array();
$returnArrayMain=array();
while ($noLines>0)
{
$resultArray=array();
$result = $dac->area_detail($add[$noLines-1]);
$count=mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$resultArray[]=array('area_id' => $row['area_id'],'area_name' => $row['area_name'],'area_GISlat'=>$row['area_GISlat'],'area_GISlon'=>$row['area_GISlon']);
}
array_push($returnArray, $resultArray) ;
$noLines = $noLines-1;
}
$returnArrayMain = array_unique($returnArray);
echo json_encode($returnArrayMain);
?>
Here is solution with a testing associative array:
// this is testing array as you are using:
$resultArray = array(
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 11,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3')
);
// take a temporary arry
$temporaryArr = array();
// initialize key's array
$arrayKey = array();
foreach ( $resultArray as $key => $values ) {
if ( !in_array($values, $temporaryArr) ) {
$temporaryArr[] = $values; // store values in temporary array
$arrayKey[$key] = true; // store all keys in another array
}
}
// now use array_intersect_key function for intersect both array.
$requiredArr = array_intersect_key($resultArray, $arrayKey);
echo "<pre>";
print_r($requiredArr);
Result:
Array
(
[0] => Array
(
[area_id] => 12
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
[1] => Array
(
[area_id] => 11
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
)
Removed duplicate arrays.
From PHP Manual:
array_intersect_key — Computes the intersection of arrays using keys for comparison
Side note:
Also add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL);
ini_set('display_errors', 1);
try this
$returnArrayMain = array_map("unserialize", array_unique(array_map("serialize", $resultArray)));
try this..
$returnArrayMain = uniqueAssocArray($returnArray, 'area_id');
echo json_encode($returnArrayMain);
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= ...
}
else
{
$replace=true;
}
if ($replace) $uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}
Chaps,
I am trying to get attributes of the 'file' node in the following XML with SimpleXml but every time is gives me back null. I have successfully got the attributes for the study node but fail to get the 'file' atts .
here is the xml :
<?xml version="1.0" encoding="UTF-8"?>
<studies>
<study uid="1.3.12.2" acc="181">
<date>20051218</date>
<time>2156</time>
<ref>CG</ref>
<desc>Abdomen</desc>
<id></id>
<path>S00001</path>
<modality>CR</modality>
<reports>
<file cat="UNK" date="20141124">Card_Cloud.txt</file>
</reports>
</study>
and here is my code :
$studyXML = new SimpleXMLElement($studyXML);
$studyXML_array = array();
foreach ($studyXML ->study as $study)
{
// Getting uid and accession from XML attributes
$uid = (!empty($study)) ? (String)$study->attributes()->uid : '';
$acc = (!empty($study)) ? (String)$study->attributes()->acc : '';
// Getting the reports and putting them in an array
$reports = array ();
foreach($study->reports as $rep)
{
$cat = (String)$rep->attributes()->cat;
$reports[] = (String)$rep->file;
}
// Constructing the xml as an array
$studyXML_array[] = array
(
'uid' => $uid,
'acc' => $acc,
'date' => (String)$study->date,
'reports' => $reports
);
}
I can get "uid" and "acc" but I can't get "cat" and "date" inside file node.
When I look at the array of the xml in my debug variables I can see uid and acc attributes but no sign of cat and date attributes.
I Would really appreciate any help.
I prefer to stick to SimpleXML as all my code is using that so far.
Cheers
This is how I did it based on Ghost answer.
$reports = array ();
foreach($study->reports->file as $rep)
{
$temp = array();
$temp['repName'] = (String)$rep;
// Getting cat and date attributes of the report
foreach($rep->attributes() as $key => $rep)
{
$temp[$key] = (string) $rep;
}
$reports[] = $temp;
}
If you're trying to use print_r()/var_dump() to check, then it will do no justice. But it is there, try to traverse to it along with using ->attributes() inside the foreach as well:
$studyXML = new SimpleXMLElement($studyXML);
$studyXML_array = array();
foreach ($studyXML ->study as $study)
{
// Getting uid and accession from XML attributes
$uid = (!empty($study)) ? (String)$study->attributes()->uid : '';
$acc = (!empty($study)) ? (String)$study->attributes()->acc : '';
// Getting the reports and putting them in an array
$reports = array();
// loop each attribute
foreach($study->reports->file->attributes() as $key => $rep)
{
$reports[$key] = (string) $rep;
}
// Constructing the xml as an array
$studyXML_array[] = array(
'uid' => $uid,
'acc' => $acc,
'date' => (String) $study->date,
'reports' => $reports
);
}
echo '<pre>';
print_r($studyXML_array);
Sample Output:
Array
(
[0] => Array
(
[uid] => 1.3.12.2
[acc] => 181
[date] => 20051218
[reports] => Array
(
[cat] => UNK
[date] => 20141124
)
)
)
Hi can somebody help me with building an extended addslashes function, which will work with mixed combination of objects and arrays. For example i have this Object:
$object = new stdClass;
$object2 = new stdClass;
$object2->one = "st'r2";
$object3 = new stdClass;
$object3->one = "st'r3";
$object->one = "s'tr";
$object->two = array($object2);
$object->obj = $object3;
And i would like to get this object back escaped and with the same structure.
I have started some experiments and i get something like this:
function addslashes_extended($arr_r){
if(is_array($arr_r)){
foreach ($arr_r as $key => $val){
is_array($val) ? addslashes_extended($val):$arr_r[$key]=addslashes($val);
}
unset($val);
}else if(is_object($arr_r)){
$objectProperties = get_object_vars($arr_r);
foreach($objectProperties as $key => $value){
is_object($value) ? addslashes_extended($value):$arr_r->{$key}=addslashes($value);
}
}
return $arr_r;
}
But this is not going to work, i have to work with passing by reference i think, but i have no clue how, other solutions would be nice to have too, thanks in advance!
Try this (using array_walk):
error_reporting(E_ALL ^ E_STRICT);
ini_set('display_errors', 'on');
$data = array(
"fo'o",
'bar' => "foo'bar",
'foobar' => array(
1, 2, 'someObj' => json_decode('{"prop1": "a", "prop2": "b\'c"}')
)
);
class Util
{
public static function addslashes_extended(&$mixed) {
if (is_array($mixed) || is_object($mixed)) {
array_walk($mixed, 'Util::addslashes_extended');
}
elseif (is_string($mixed)) {
$mixed = addslashes($mixed);
}
}
}
Util::addslashes_extended($data);
print_r($data);
Output ( http://codepad.org/nUUYKWrn ):
Array
(
[0] => fo\'o
[bar] => foo\'bar
[foobar] => Array
(
[0] => 1
[1] => 2
[someObj] => stdClass Object
(
[prop1] => a
[prop2] => b\'c
)
)
)
To pass by reference, you use & before the variable name, quick example:
function inc(&$var) {
$var++;
}
$x = 5;
inc($x);
echo $x; //Prints: 6