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

时间:2016-06-02 01:36:22

标签: php arrays

我是php和mysql的新手,所以这可能是一个简单的语法错误或其他东西,但我没有运气使用其他的例子。

我的数据库中的数组(JSON编码):

var vectorLayer = map.getLayer('myVectorLayer');
vectorLayer.fire('click');

从UserData获取JSON编码数组:

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

结果:

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];
}

为什么要替换“echo $ json [0];” “echo $ json ['option1'];”虽然阵列被解码了,但是不行?

编辑:把它整理好了!通过使用以下方法诀窍:

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

1 个答案:

答案 0 :(得分:5)

这不是存储数据的最佳方式。如您所见,它以PHP code的形式存储在您的数据库中。如果你想访问这个数组中的变量,那么你将会遇到困难!

更多“常见”实现目标的方式是将 NAME_PATTERN = /([\w\-\']{2,})([\s]+)([\w\-\']{2,})/ EMAIL_PATTERN = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i PHONE_PATTERN = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/ def valid_name?(name) !!name.match(NAME_PATTERN) end puts "Enter your first and last name (John Doe): " while (name=gets) names = name.split(" ", 2) if valid_name?(name) puts "Great, that looks like it could work." break else puts "Invalid entry, please enter first and last name. To exit press ctrl+c." end end def valid_email?(email) !!email.match(EMAIL_PATTERN) end puts "Enter your email address (joe@info.com): " while (email = gets) if valid_email?(email) puts "Great, that looks like it could work." break else puts "Invalid email address entered. Please try again. To exit press ctrl+c." end end puts "Enter your phone number including area code (numbers only): " def valid_phone?(number) !!number.match(PHONE_PATTERN) number = number.to_s area_code = number.length == 10 ? "(#{number[0..2]}) " : '' office_code = number[-7..-5] specific_line = number[-4..-1] "#{area_code}#{office_code}-#{specific_line}" end while (number=gets) if valid_phone?(number) puts "Great, that looks like it could work." break else puts "Invalid phone number entered. Please try again. To exit press ctrl+c." end end print "User: #{names}\nPhone: #{valid_phone?(number)}\n Email: #{email}" 存储在数据库中并进行访问。

JSON

作为@Sean noted in his comment,您将获取一组数据而不是一行。您可以通过利用$MYSQLI->fetch_assoc()返回关联数组来完成此操作。

修改

这是对您的问题的修改。您仍然将字符串数组存储为json。这就是你无法访问它的原因。我假设你有一个实际的数组。这是您想要存储所述数据的方式:

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

echo $json->someotherthing;