<?php
$json= '{
"fields" :
[
{
"name" : "news_title",
"type" : "text",
"value" : "old title"
},
{
"name" : "news_content",
"type" : "textarea",
"value" : "old content"
}
]
}';
echo $json;
$jsonInPHP = json_decode($json,true);
$results = count($jsonInPHP['fields']);
for ($r = 0; $r < $results; $r++){
// look for the entry we are trying to find
if ($jsonInPHP->fields[$r]['name'] == 'news_title'
&& $jsonInPHP->fields[$r]->value == 'old title'){
// remove the match
unset($jsonInPHP->fields[$r]);
if(empty($jsonInPHP->fields[$r]->value))
{
$jsonInPHP['fields'][$r]['name'] == 'news_title';
$jsonInPHP->fields[$r]->value=='no';
}
break;
}
}
function gog($status)
{
$results = count($status->fields);
for ($r = 0; $r < $results; $r++){
$status->fields[$r]->value == 'old rr';
}
}
$jsonInPHP->fields = array_values($jsonInPHP->fields);
echo json_encode($jsonInPHP);
?>
i want to change after searching from
'{"fields":[{"name":"news_title","type":"text","value":"old title"},{"name":"news_content","type":"textarea","value":"old content"}]}'
to
'{"fields":[{"name":"news_title","type":"text","value":"My new title"},{"name":"news_content","type":"textarea","value":"My new content"}]}'
Check official docs of json_decode Second parameter of function json_decode($json,true); (in your case true) determines whether result will be converted to associative array. If you want to use result as objects set that value to false or better omit that at all.
Related
I want to select id and property_name just like i would on mysql
select property_name,_id from properties from properties
In mongodb that is
> db.properties.find({
...
... },{
... "property_name": 1
... }
... );
{ "_id" : ObjectId("6098e4743569ea6d9d6985b2"), "property_name" : "Aero Club" }
{ "_id" : ObjectId("6098f8e7a3397059ef264932"), "property_name" : "Radisson Blu Hotel" }
>
This is my php code
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->properties;
//echo $collection->count();
echo "<pre>";
print_r($collection->find(array(), array("property_name" => 1))).iterator_to_array();
echo "</pre>";
I don't see the array of id and property_name returned anywhere so its hard fro me to loop through the returned object.
After returning the id and property, i wan't to translate this query into mongodb
select * from rooms where (has_sauna = 'yes' OR has_elevator = 'yes' or has_television = 'yes') and (price between "200" and "300" )
How can i fix the php query?.
Have you tried this one?
$collection->find(
{ $and: [
{ $or: [
{has_sauna : 'yes'},
{has_elevator : 'yes'},
{has_television : 'yes'}
]},
{ price: {$gt : 200, $lt : 300} }
]}
);
I can get the id and property name like this
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->properties;
$cursor = $collection->find();
foreach ($cursor as $document) {
echo '"_id": '.$document["_id"]."<br />";
echo '"property name": '.$document["property_name"]."<br />";
}
While this works, i would like to know how to specify what columns/fields to find.
I have the following string thatI convert into a json array. All I am trying to do put together keys with the same value for id_number and sum the amount to each of these keys and print the resulting value outside the loop.
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$json_response = json_decode($response, true);
//Start NHIF
foreach ($json_response['nhif'] as $nhif) {
echo ''.$nhif{"id_number"}.' '.$nhif{"amount"}.' '.$nhif{"date"}.'<br/>';
}
//END NHIF
My expected output is:
#id_number #amount
AA112233 20
12345678 5
Any workaround this?
You can use array_reduce to sum the amount values by id_number:
$sums = array_reduce($json_response['nhif'], function ($c, $i) {
$c[$i['id_number']] = (isset($c[$i['id_number']]) ? $c[$i['id_number']] : 0) + $i['amount'];
return $c;
}, array());
print_r($sums);
Output:
AA112233 20
12345678 5
Demo on rextester
If you're using PHP7, this
isset($c[$i['id_number']]) ? $c[$i['id_number']] : 0
can be simplified to
$c[$i['id_number']] ?? 0
You can do solve this problem using an array
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$json_response = json_decode($response, true);
$results = array(); // will map the unique keys with it's sum
//Start NHIF
foreach ($json_response['nhif'] as $nhif) {
if(!isset($results[$nhif['id_number']])) // new key initialized
$results[$nhif['id_number']] = $nhif['amount'];
else
$results[$nhif['id_number']] += $nhif['amount'];
}
//END NHIF
foreach($results as $key => $value) {
echo $key .' '.$value; // printing the result
}
Sort the array [If the data is not sorted otherwise do not need to sort].
Do the for loop and summation.
Try with this code sample, there are many other ways to solve this problem depending on problem solving skill.
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$data = json_decode($response, true);
usort($data['nhif'], function($a, $b) {
return $b['id_number'] <=> $a['id_number'];
});
//Start NHIF
$amount = 0;
$id_number = null;
foreach($data['nhif'] as $nhif) {
if(($nhif['id_number'] != $id_number) && ($id_number != null)){
echo $id_number. "\t". $amount . "<br />";
$id_number = $nhif['id_number'];
$amount = $nhif['amount'];
}
else{
$id_number = $nhif['id_number'];
$amount = $amount + $nhif['amount'];
}
// echo ''.$nhif{"id_number"}.' '.$nhif{"amount"}.' '.$nhif{"date"}.'<br />';
}
echo $id_number. "\t". $amount . "<br />";
//END NHIF
You could create a new array for example $r and check if the key for $nhif['id_number'] already exists.
If it does, add value for $nhif['amount']using +=. If it does not, set the value using =
This example uses the ternary ?: operator:
$r = [];
foreach ($json_response['nhif'] as $nhif) {
isset($r[$nhif['id_number']]) ? $r[$nhif['id_number']] += $nhif['amount'] : $r[$nhif['id_number']] = $nhif['amount'];
}
Demo
Mongodb gives the following:
{
"_id" : ObjectId("55d1d8ea464498a8338b4567"),
"appuserfirstname" : "Bhatti",
"appuserlastname" : "Singh",
"appusermiddlename" : "Tripatpal",
"appuseremail" : "tripat.90#gmail.com",
"appusergoogleid" : [
{ "id" : "APA91bFPqNjK5bWdTe6bAniDV8ZlmG5vL3Q1qRz_WGAasOMu_WBbzoorWI2uCU7yC4IS-yggNGQvL7oUp5YhiejOC1TB4bFQspKj4AUZ05-IEL9DJiI2oNwIl5YwW5zyBVqrTMNWFF2B" }
],
"usercreationdate" : ISODate("2015-08-17T18:21:54Z"),
"status" : "0",
"userfollows" : [
{ "following" : ObjectId("55cd8dae46449867738b4567") }
]
}
I want the ids that are in following. but it always gives me empty string
<?php
$appuserid = '123456789';
$appuserscollection = $this->database->createCollection("appusers");
$followers = array('_id' => new MongoId($appuserid));
$s = "";
$result = $appuserscollection->find($followers);
foreach($result as $document) {
$s.=$document['userfollows'];
}
echo $s;
?>
With
$appuserscollection = $this->database->createCollection("appusers");
you create a new collection. And a new collection is always empty
you could try
$collection = new MongoCollection($this->database, 'appusers');
I'm trying to search my collection for all occurrences where the body property contains all of the search keywords.
Example string - "The black cat is definitely purple."
Keywords "black", "purple" would return the string.
Keywords "black", "dog" would not return that string.
I've been cruising some topics and Googling, but cannot seem to find the proper syntax to do this.
Currently, I am taking an string of keywords separated by commas, exploding it into an array, and then putting that into a MongoRegex Object. I know my syntax is off, because when I send just one keyword it works, but when there is more than one, I do not get any results that I would expect to get.
Current Approach:
<?php
function search_topics($array)
{
include_once('config.php');
$collection = get_connection($array['flag']);
$x = 0;
$string = null;
$search_results = null;
$keywords = explode(',', $array['search']);
$end_of_list = count($keywords);
while ($x < $end_of_list)
{
$string = $string."/".$keywords[$x];
$x++;
if($x >= $end_of_list)
{
$string = $string."/i";
}
}
if ($string != null)
{
try
{
$regex_obj = new MongoRegex($string);
$cursor = $collection->find(array('body' => $regex_obj));
}
catch (MongoCursorException $e)
{
return array('error' => true, 'msg' => $e->getCode());
}
foreach($cursor as $post)
{
$search_results[] = $post;
}
if ($search_results != null && count($search_results) > 1)
{
usort($search_results, 'sort_trending');
}
return array('error' => false, 'results' => $search_results);
}
else
{
return array('error' => false, 'results' => null);
}
}
?>
So, if I send the string black in $array['search'], my object is formed with /black/i and would return that string.
If I send the string black,cat in $array['search'], my object is formed with /black/cat/i and returns null.
Can anyone point me in the right direction with this regex syntax stuff?
Thanks in advance for any help!
Nathan
Instead of regular expressions, I would suggest you look at MongoDB's text search functionality instead, which is specifically made for situations like this: http://docs.mongodb.org/manual/core/text-search/
You would use that like this (on the MongoDB shell):
use admin
db.runCommand( { setParameter: 1, 'textSearchEnabled' : 1 } );
use test
db.so.ensureIndex( { string: 'text' } );
db.so.insert( { string: "The black cat is definitely purple." } );
db.so.runCommand( 'text', { search: '"cat" AND "dog"' } )
db.so.runCommand( 'text', { search: '"cat" AND "purple"' } )
A command doesn't return a cursor, but instead it will return one document containing all the query results in the results field. For the last search command, the result is:
{
"queryDebugString" : "cat|purpl||||cat|purple||",
"language" : "english",
"results" : [
{
"score" : 2.25,
"obj" : {
"_id" : ObjectId("51f8db63c0913ecf728ff4d2"),
"string" : "The black cat is definitely purple."
}
}
],
"stats" : {
"nscanned" : 2,
"nscannedObjects" : 0,
"n" : 1,
"nfound" : 1,
"timeMicros" : 135
},
"ok" : 1
}
In PHP, for the runCommand to turn on text search, you'd use:
$client->database->command( array(
'setParameter' => 1,
'textSearchEnabled' => 1
) );
And the text search itself as:
$client->database->command( array(
'text' => 'collectionName',
'search' => '"cat" AND "purple"'
) );
I have in my table records that are related one to another by a parentId field. When fetching them from the DB I need to create JSON array of objects where the child records are added to 'children' property of parent objects :
[{
//main object
children : [
{
//#1st level children object
children: [
{
//#2nd level children object
}
]
}
]
},
{
(...)
]
But if there are no records with parentId equal to current record, then this property shouldn't be added to the object.
Right now I'm building the JSON string manually :
//first get the parents
$q = 'SELECT * FROM table WHERE parentId = 0';
$r = mysql_query($q);
$x=1;
$nr = mysql_num_rows($r);
while($e = mysql_fetch_array($r)){
if($x==1){
echo '[ { ';
}
else{
echo ' { ';
}
if($e['leaf']==1){
$leaf = 'true';
} else {
$leaf = 'false';
}
echo '"EndDate" : "'.str_replace('T00:00:00','',$e['EndDate']).'",
"Id" : '.$e['Id'].',
"Name" : "'.$e['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e['BaselineStartDate']).'"';
if($leaf){
echo ',"leaf": '.$leaf.'';
}
childs($e['Id'], $x, $nr);
if($x<$nr){
echo ',';
}
$x++;
}
if($x>1){
echo ']';
}
function childs($id, $x, $nr, $x2='', $nr2=''){
//now see if there are childern
$q2 = 'SELECT * FROM table WHERE parentId = "'.$id.'" ';
$r2 = mysql_query($q2);
$nr2 = mysql_num_rows($r2);
if($nr2>0){
echo ',"children": [ ';
$x2 =1;
while($e2 = mysql_fetch_array($r2)){
if($e2['leaf']==1){
$leaf2 = 'true';
}
else{
$leaf2 = 'false';
}
echo '{
"EndDate" : "'.str_replace('T00:00:00','',$e2['EndDate']).'",
"Id" : '.$e2['Id'].',
"Name" : "'.$e2['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e2['BaselineStartDate']).'",
"leaf" : "'.$leaf2.'"';
childs($e2['Id'],$x,$nr,'',$x2,$nr2);
if($x2<$nr2){
echo ',';
}
$x2++;
}
echo '] }';
}
else{
echo ',"children" : []}';
}
}
Is there an easy way to make this code more robust using some built-in PHP features like fetch_assoc or something like that?
You should rather..
Fetch the results from the database
Reformat as per the requirement (related code you can use with some alteration PHP Create a Multidimensional Array from an array with relational data
Then finally, json_encode the resulting array