duandaotuo5542
duandaotuo5542
2014-02-04 09:52

如何将此json数组保存到MYSQL数据库

已采纳

I want to save this json array that my fb-login returns to a database. However I don't really know how to convert that into a string using php.

[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]

I have tried this code below but I am even not quite sure anymore whether what the fb login return is a json array or not.

$json = '{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}';

var_dump(json_decode($json));

How would I be able to save the different sports to my database in a string?

Any help would be much appreciated.

Thanks.

EDIT: The upper part returns NULL.


SECOND EDIT:

if (array_key_exists('sports', $me)){


                    $json = '$me['sports']'; PROBLEM IS HERE
                    $data = json_decode($json, true);
                    $sports = array();
                    foreach ($data as $item) {
                        $sports[] = $item['name'];
                    }

                    $user->fb_sports = $sports;
                }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • dongxin8709 dongxin8709 7年前
    $json = '[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]';
    $data = json_decode($json, true);
    $sports = array();
    foreach ($data as $item) {
        $sports[] = $item['name'];
    }
    

    if you want commas separating them:

    $output = implode(', ', $sports);
    
    点赞 评论 复制链接分享
  • dooso0594 dooso0594 6年前
    $string=mysql_real_escape_string($json);
    
    点赞 评论 复制链接分享
  • dsdf64562672 dsdf64562672 7年前
    $json1 = '{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}';
    $json2 = '[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]';
    
    var_dump(json_decode($json1,true));
    var_dump(json_decode($json2,true));
    

    watch the difference

    点赞 评论 复制链接分享
  • dongnuoyi8833 dongnuoyi8833 7年前

    use :

     $json = serialize($json);
    
    点赞 评论 复制链接分享
  • duanjuelian4640 duanjuelian4640 7年前

    If var_dump(json_decode($json)) returns what you'd expect just save $json directly into the database.

    点赞 评论 复制链接分享

相关推荐