mongodb find nested field not work in php - php

i am new on php and mongodb. i want to find all data which match the condition in php.
the following mongodb structure:
'Food' =>
array (size=4)
'_id' =>
object(MongoId)[36]
public '$id' => string '587e4a89974711036c97d3e5' (length=24)
'CaseId' => string 'c002' (length=4)
'Level' => string '4' (length=1)
'food' => string 'banana' (length=6)
i try to search 'food' value in Food object. i have do some research. i have some method to deal with. however, i cannot find anything. i don't know where wrong? hope someone can teach me.
here is my query:
$cursor=$collection->find(array("Food.food"=>array('$in'=>["banana"])));
$cursor=$collection->find(array('Food'=>array('food'=>"banana")));
$cursor=$collection->find(array('Food.food'=>"banana"));
after i research, i know MongoDB supports dot notation. resource from
enter link description here
also i find some get nested field method from
enter link description here
i following the link 2 to typing in mongodb compass. i can get the result i want, but when i follow the structure to enter in php. it have not any result.
what happen in these code?? i am confused. thank you.

i find other method to solve this problem. if someone meet this case like me, you can try below method.
$query= array(
'$match'=>array('Food.food'=>'banana')
);
$cursor=$collection->aggregate($query);
you can type $cursor['result'] to receive the searching result.

Related

Laravel Validation - How to check if a value exists in a given array?

So, okay i tried a lot of rules from validation docs but all give me same error saying
Array to string conversion
Here is how I add the array:
$this->validate($request,[
'employee' => 'required|in:'.$employee->pluck('id')->toArray(),
],[
'employee.in' => 'employee does not exists',
]);
Any hint on how to achieve this?
i created a custom validator but still passing array seems to be not possible
Implode the array as a string and join it on commas.
'employee' => 'required|in:'.$employee->implode('id', ', '),
This will make the correct comma separated string that the validator expects when making an in comparison.
Edit
This still works, but is not the Laravelesque way of doing it anymore. See the answer by #nielsiano.
Update: You are now able to use the Rule class instead of imploding values yourself as described in the correct answer. Simply do:
['someProperty' => ['required', Rule::in(['needed', 'stuff'])]];
As mentioned in the 'validating arrays' section in the documentation: https://laravel.com/docs/5.6/validation#validating-arrays

Symfony 2 PHP Template Engine rendering Objects

I kind of prefer using PHP Template Engine to Twig in symfony2 due to some flexibility, and something I am more used to.
For instance, I will like to use things like 'ternary If' when printing out some stuff.
My problem now is that, My data got rendered on the template as Objects. using (array) seems not to help as well as I ended up getting things like;
array (size=4)
'�news\newsBundle\Entity\News�id' => int 1
'�news\newsBundle\Entity\News�title' => string 'News title 1' (length=12)
'�news\newsBundle\Entity\News�body' => string 'Some body text' (length=14)
'�news\newsBundle\Entity\News�createdDate' =>
object(DateTime)[306]
public 'date' => string '2014-11-05 19:41:48.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/London' (length=13)
How do I get results like a normal array e.g array('id'=> int 1) without the namespace stuff in it.
Thanks in advance
You may want to change hydration mode in your queries to get entities as arrays:
http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#array-hydration
Symfony2, Doctrine 2: getResult Object

Creating an API to pass an Array result in PHP

I am not an expert with PHP. I am creating an API in order to get some information from one of my website.
Here is the result of api.php:
array (size=4)
'price' => string '29.90' (length=5)
'activation_charge' => string '50.00' (length=5)
'decoder_price' => string '0.00' (length=4)
'is_offer' => int 0
I would like to create an API which would send these information. Here is the sample API call :
www.example.com/api.php?product=11&user=kiran
How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
Thanks
How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
JSON is a popular choice
json_encode http://php.net/json_encode
json_decode http://uk3.php.net/json_decode
XML is also another popular choice
http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
CSV is popular depending on the data/application (and variants of; pipe-delimiter, etc)
explode http://php.net/explode
If you want to return it to Javascript for example. The easiest way is to use JSON.
echo json_encode( $array ) ;
Which will output something like:
{ "price" : 29.9, "activation_charge" : 50.0, "decoder_price" : 0.0, "is_offer" : 0 }
Of course you can create your own format and decode it on the other side.

Failing preg_match pattern over entirely valid value

I used regexpal.com to test my regexp against the data Wordpress is trying to compare to and it fails, look at this and tell me if you see the problem?
The regexp
"#^json/(.+?)/?([a-zA-Z0-9]*)?$#"
The content to match
json/trips
These works, the previous one doesn't
json/trips/0
json/trips/13
json/fullticket/9805048001130122361809
If I try all these in regexpal they all work, but in wordpress, only the one that doesn't contain the id of the element I want to fetch fails the others work fine.
Interrestingly enough, the $matches return this:
array
0 => string 'json/trips' (length=10)
1 => string 't' (length=1)
2 => string 'rips' (length=4)
Try this regexp instead :
#^json/([^/]+)/?([a-zA-Z0-9]*)?$#
Output :
Array
(
[0] => json/trips
[1] => trips
[2] =>
)
The answer after tweaking the wordpress rewrite rule a bit more ends up being:
data/([^/]+)(/([a-zA-Z0-9\-]*))?$
Note: i changed json to data in the new scenario so i don't mess up the custom post type rules

Better data structure or algorithm than iterative searching on multidimensional arrays to find corresponding values?

For a site I am working on I use a library to get a list of states. It returns a numerically indexed array of states, each with three keys: stateCode, stateName, and stateSeg. It looks like this:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
array
'stateCode' => string 'AZ' (length=2)
'stateName' => string 'Arizona' (length=7)
'stateSeg' => string 'arizona-az' (length=10)
I often find myself with one of the three values and needing to look up its corresponding value. To do this I find myself constantly having to iterate through the array of states to find the data I need. Like this:
foreach ($this->data['stateList'] as $state)
{
if ($state['stateCode'] == $searchParams['state'])
{
$stateSeg = $state['stateSeg'];
break;
}
}
$url = BASEURL . '/' . $stateSeg . ".html";
This seems inefficient to me. I think the most efficient solution I’ve been able to come up with is to turn states into objects and put them in array with multiple keys for stateCode, stateSeg, and stateName each pointing to the same state object, so they can be referenced like this:
stateList[‘CA’]->getStateSeg();
or
stateList[‘Arizona’]->getStateCode();
or
stateList[‘alaska-ak’]->getStateName();
etc…
This also seems like kind of a hack which would result in a rather large array (150 keys pointing to 50 objects) with replicated data (keys replicating data stored within objects).
Anyway, just thought I’d see if there is some kind of pattern for this type of problem. This array of states isn't the only thing I’ve come across where I’ve had to do this sort of iterative searching on multidimensional arrays to find corresponding values.
Question is tagged PHP and the code above is in PHP, but I am interested in elegant solutions in any language.
If php supports references and I know the state, I'd just pass a reference to the appropriate array element and extract from it the necessary field.
Alternatively, if you never know in advance what state you can get, create and use a map (associative container/array), let its efficient implementation take care of quickly finding whatever you need. Seems like you may need several of them.
Also, I wonder if you could get rid of everything except the "alaska-ak" strings. The data appears highly redundant.
I think your basic idea with the object and the arrays is not that bad, but instead of creating actually objects, I would just refer to the existing objects (better: array data). Let's see your original list again:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
...
Each state object has an identifier, the array key: 0, 1, 2, ... .
All you need to do is to create three indexes based on key. You use the value as key (e.g. "AL" for "stateCode" index) and as value you take the array index, 0:
$indexStateCode['AL'] = 0;
You can then already look this up quickly:
$states[$indexStateCode['AL']];
Encapsulate this into a class with ArrayAccess and then on request instantiate the state object. You don't need it earlier.
Could you store the states in a mysql/sqlite table and use the database engine to do the lookup?
This seems inefficient to me
It isn't. Even worse-case, iterating through 50 items is probably an order of magnitude faster than querying a db.
a library to get a list of states
Not sure why you'd need a library to do this. But I'd either change the library to return the array how you need it, or wrap it in another module.
The data is somewhat redundant... All you need is two items: the state code and the state name. You can construct the "state seg" from those two. So keep a state code map and a state name map.

Categories