PHP Associative array from encoded data -
i'm kinda new php , mysql simple syntax error or i'm having no luck using other examples.
the array in db (json encoded):
["[\"option1\"=\u003e\"1\",\"someotherthing\"=\u003e\"abc\"]",""]
fetching json encoded array userdata:
if ($stmt = $con->prepare("select userdata users 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 replacing "echo $json[0];" "echo $json['option1'];" won't work, although array decoded?
edit: got sorted! trick using following:
if ($stmt = $con->prepare("select userdata users 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']; }
this isn't best way go storing data. see, it's being stored in database php code
. if you're looking access variables in array you're going have hard time!
a more "common" way of achieving you're after storing json
in database , accessing it.
//....other code.... $data = $result->fetch_assoc(); $json = json_decode($data); echo $json->someotherthing;
as @sean noted in comment, you're fetching collection of data instead of 1 row. can harnessing $mysqli->fetch_assoc()
return associative array.
edit
this edit question. you're still storing string array json. that's why can't access it. assume have actual array. way you'd want store said data:
// example array $array = array('test' => 'hello', 'derp' => 'herp'); // encode $json = json_encode($array); // store // mysqli insert, etc...