如何在php中将字符串(用逗号分隔)转换为多维json数组

时间:2016-08-01 12:21:18

标签: php mysql arrays json

如何将带有逗号的字符串从数据库转换为名称为

的多维数组

我有一个列名是工作时间,因为我们存储了数据,如上午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"}}]]

1 个答案:

答案 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字符串。