doujiao1814 2016-06-02 01:36
浏览 86
已采纳

来自编码数据的PHP关联数组

I'm kinda new to php and mysql so this could be something as simple as a syntax error or something but I'm having no luck with using other examples.

The array in my db (JSON encoded):

["[\"option1\"=\u003E\"1\",\"someotherthing\"=\u003E\"abc\"]",""]

Fetching JSON encoded array from UserData:

if ($stmt = $con->prepare("SELECT UserData FROM users WHERE Username=?")) {
    $stmt->bind_param("s", $Username);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $json = json_decode($data['UserData']);
    echo $json[0];
}

Result:

["option1"=>"1","someotherthing"=>"abc"]

Why is it that replacing "echo $json[0];" with "echo $json['option1'];" won't work, although the array is decoded?

EDIT: got it sorted! Does the trick by using the following:

if ($stmt = $con->prepare("SELECT UserData FROM users WHERE Username=?")) {
    $stmt->bind_param("s", $Username);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $json = json_decode($data['UserData']);
    $array = json_decode(json_encode($json),true);
    echo $array['test'];
}
  • 写回答

1条回答 默认 最新

  • dongwen1935 2016-06-02 01:46
    关注

    This isn't the best way to go about storing data. As you see, it's being stored in your database as a PHP code. If you're looking to access the variables in this array then you're going to have a hard time!

    A more "common" way of achieving what you're after is storing JSON in the database and accessing it.

    //....other code....
    $data = $result->fetch_assoc();
    $json = json_decode($data);
    
    echo $json->someotherthing;
    

    As @Sean noted in his comment, you're fetching a collection of data instead of one row. You can do that by harnessing $MYSQLI->fetch_assoc() to return an associative array.


    Edit

    This is an edit to your question. You're still storing a string array as json. That's why you can't access it. I assume you have an actual array. This is the way you'd want to store said data:

    // example array
    $array = array('test' => 'hello', 'derp' => 'herp');
    // encode it
    $json = json_encode($array);
    // store it
    // DO YOUR MYSQLI INSERT, ETC...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误