在API调用中将字符串转换为数组

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.

douya8978
douya8978 您可以点击此链接:stackoverflow.com/questions/6243051/...
大约 3 年之前 回复
dst3605528
dst3605528 使用serialize()和unserialize()或使用会话。
大约 3 年之前 回复
douyuan3842
douyuan3842 你是如何尝试使用json_encode的?请告诉我们......
大约 3 年之前 回复

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐