0

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.

3
  • How did you try with json_encode ? Show us please... Commented Jul 28, 2017 at 8:33
  • Use serialize() and unserialize() or do it with sessions. Commented Jul 28, 2017 at 8:36
  • You can follow this link: stackoverflow.com/questions/6243051/… Commented Jul 28, 2017 at 8:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.