如何将带有逗号的字符串从数据库转换为名称为
的多维数组我有一个列名是工作时间,因为我们存储了数据,如上午10:00,下午1:00,下午2:00,下午5:00
我的查询是
$sqlbranch = "SELECT * FROM branch WHERE Bank_name='$bankname'";
$resultbranch = mysql_query($sqlbranch);
$branchArray = array();
if (mysql_num_rows($resultbranch) > 0) {
while ($row = mysql_fetch_assoc($resultbranch)) {
$branchArray['branches'][] =array('Working Hours' =>$row['Working_hours']));
现在我想将数据转换为json数组
我希望json数据看起来像
"branches":[{"working_hours":[{"Morningtime":{"begin_time":"10:00", "end_time":"15:30"},
"eveningtime":{"begin_time":"16:00", "end_time":"18:30"}}]]
答案 0 :(得分:0)
首先,$hours = explode(',', $row['Working_hours'])
。
接下来,foreach ($hours as $hour) { $parts = explode(' ', $hour)
和if ($parts[1] == 'pm' )
会像$digits = explode(':', $parts[0])
那样爆炸,并向12
添加$digits[0]
,否则请使用$parts[0]
作为时间,并将其存储在$cHours
数组中。
之后创建一个像$branches = ['working_hours' => [ 'Morningtime' => ['begin_time' => $cHours[0], 'end_time' => $cHours[1]], 'eveningtime' => ['Morningtime' => ['begin_time' => $cHours[2], 'end_time' => $cHours[3]]
最后json_encode($branches)
让你获得json字符串。