如何将json_decoded值(仅)保存为$ var中的一个字符串

时间:2013-05-29 10:00:26

标签: php arrays json

我从javascript:$_REQUEST['fb_friend_uid']

收到以json数组发送的以下变量 然后我解码数组,然后执行var_dump

$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);

var_dump($result);

var_dump显示以下内容

array (size=360)
  0 => 
    array (size=1)
      'id' => string '263901486' (length=9)
  1 => 
    array (size=1)
      'id' => string '502533736' (length=9)
  2 => 
    array (size=1)
      'id' => string '506526230' (length=9)
  3 => 
    array (size=1)
      'id' => string '507245473' (length=9)
    etc..

我如何将所有值从'id'保存到一个新的$ var_string? - 格式如:“263901486,502533736,506526230”

目标是在sql查询中使用字符串,如下所示:

SELECT * FROM vote WHERE
vote_fb_uid IN ($var_string)

4 个答案:

答案 0 :(得分:1)

试试这个:

$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);

$res_array   = array();
foreach($result as $val){
   $res_array[]  = $val['id'];
}

$res_string = implode(",",$res_array);

答案 1 :(得分:0)

如果您希望将所有项目组合成一个长字符串,则可以尝试对数组进行内爆 http://php.net/manual/en/function.implode.php

$varString = implode(',', $_REQUEST['fb_friend_uid'])

答案 2 :(得分:0)

我真的不懂PHP,但是看一下这些文档,你应该可以写下以下内容:

$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);

$res_array = array_map(function ($val) { return $val['id']; });

$res_string = join(",", $res_array);

(改编自Prasanth Bendra的回答。)

答案 3 :(得分:0)

试试这个

$string = json_encode($ar);
$result = json_decode($string, true);

$res_array   = array();
foreach($result as $val){
   $res_array[]  = $val['id'];
}

$res_string = "'".implode("','", $res_array)."'";

$qry = "SELECT * FROM vote WHERE vote_fb_uid IN ($res_string)";