I am passing an array as a string in parameter to an api in php like this:
http://xx.xx.xx.xx/api.php?query="array(done = 1)"
In my api file, I have used this array to hit a mongodb query:
$query = $_REQUEST['query'];
$cursor = $collection->find($query);
But this didn't work. When I hard-coded array(done = 1)
into the find
query, it seems to work fine.
if (array('done' => 1) == $query) {
echo "Y";
}
else {
echo "N";
}
The above code prints N
. So I guess it's because $query
is being passed as a string.
PS: I also tried json_encode, json_decode and unserialize but it didn't work. I might be doing omething wrong here.
Well make bit change in your query string, you passing in api request.
Suppose belowis your array.
$array = array('done' => 1, 'message' => 'success');
USE array_map_assoc
function with some customization, which make easy to implode associative array
function array_map_assoc( $callback , $array ){
$r = array();
foreach ($array as $key=>$value)
$r[$key] = $callback($key,$value);
return $r;
}
Generate your data to be sent in api our data
$queryString = implode('&',array_map_assoc(function($k,$v){return "$k=$v";},$array));
Now send your data with API
$url = "http://xx.xx.xx.xx/api.php?" . $queryString ;
Now use print_r($_GET)
in your API page and you will receive data like below
Array
(
[done] => 1
[message] => success
)
This make your code easy to handle and use in either if condition or sql query.