我使用PHP从mysql数据库中获取表数据。数据库中的一个字段(memberProperties)是一个像这样输出的数据数组:
{
"title":"-",
"first_name":"Joe",
"last_name":"Bloggs",
"role":"Senior Scientist",
"phone":"61240 652135",
"start_date":"2016-05-20",
"leave_date":"2016-05-20",
"location":null,
"team":"Engineering",
"platform":"Rockets",
"username":"joe.bloggs",
"from_ad":"true",
"full_name":"Joe Bloggs",
"display_name":"Joe Bloggs",
"mobile":null,
"company":"ACM WIDGETS"
}
如何循环浏览每个值并分配可在页面中重复使用的变量?我已根据w3schools PHP tutorial尝试执行以下操作...但它没有& #39; t似乎分别输出值。
$my_array = array($row["memberProperties"]);
list($title, $first_name, $last_name, $role, $phone, $start_date, $leave_date, $location, $team, $platform, $username, $from_ad, $full_name, $display_name, $mobile, $company) = $my_array;
echo "$title, $first_name, $last_name, $role, $phone, $start_date, $leave_date, $location, $team, $platform, $username, $from_ad, $full_name, $display_name, $mobile, $company";
答案 0 :(得分:2)
正如人们建议使用json_decode将你的字符串转换为php对象
在您的代码中,您可以使用下面的
user_activated_events_q
输出将是
$memberProperty = json_decode($row["memberProperties"]);
print_r($memberProperty->first_name)
答案 1 :(得分:1)
这是一个JSON字符串。您需要先解码它,然后才能将其用作数组。试一试:
$array = json_decode($row["memberProperties"]);
echo '<pre>'; var_dump($array); echo '</pre>';
答案 2 :(得分:0)
使用此功能:
$string_data = json_decode($array);
答案 3 :(得分:0)
您在问题中显示的值不是代替其JSON字符串,而是可以json_decode
与foreach
一样使用
$json = '{"title":"-","first_name":"Joe","last_name":"Bloggs","role":"Senior Scientist","phone":"61240 652135","start_date":"2016-05-20","leave_date":"2016-05-20","location":null,"team":"Engineering","platform":"Rockets","username":"joe.bloggs","from_ad":"true","full_name":"Joe Bloggs","display_name":"Joe Bloggs","mobile":null,"company":"ACM WIDGETS"}';
$json_array = json_decode($json,true);
foreach($json_array as $k => $v){
${$k} = $v;
}
$arr = get_defined_vars();
print_r($arr);
此处get_defined_vars()
会显示文件中的所有变量