【问题标题】:How to convert string (separated by commas)in to mutidimensional json array in php如何在php中将字符串(用逗号分隔)转换为多维json数组
【发布时间】:2016-08-01 12:21:17
【问题描述】:

如何将数据库中带逗号的字符串转换为带名称的多维数组

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

【问题讨论】:

    标签: php mysql arrays json


    【解决方案1】:

    首先,$hours = explode(',', $row['Working_hours'])

    接下来,foreach ($hours as $hour) { $parts = explode(' ', $hour)if ($parts[1] == 'pm' )$digits = explode(':', $parts[0]) 一样进行另一个分解,并将 add 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字符串。

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2021-08-09
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多