dpmp9359 2014-04-22 11:56
浏览 61
已采纳

格式化json_encode的数组

I have been searching for days to try and piece together my solution but am still struggling. I'm struggling with some php and getting it into the format I want in json-encode so I can use knockout.js.

I have a db that looks like this:

| id | name       | value                  |
| 1  | taskName   | First Task             |
| 1  | taskDetail | Enter your first task  |
| 1  | taskList   | Very Important         |
| 2  | taskName   | Second Task            |
| 2  | taskDetail | Enter your second task |
| 2  | taskList   | Important              |

I'm trying to get this response to my site with json_encode to look like this:

[
  {
    "id": "1",
    "taskName": "First Task",
    "taskDetail": "Enter your first task",
    "taskList": "Very Important"
  },
  {
    "id": "2",
    "taskName": "Second Task",
    "taskDetail": "Enter your second task",
    "taskList": "Important"
  }
]

Here is what I have so far:

$user = 1;

$task_sql = "
    SELECT *
    FROM `li_id`
    INNER JOIN `li_details`
    ON li_id.id = li_details.id
    WHERE li_id.user = '" . $user . "'";


$result = mysql_query($task_sql, $con);
$results = array();

while ($row = mysql_fetch_assoc($result)) {
    $results[] = array($row['name'] => $row['value']);
}

echo json_encode($results);

Response:

[
  {
    "taskName": "First Task"
  },
  {
    "taskDetail": "Enter first task in application."
  },
  {
    "taskList": "Important"
  },
  {
    "taskName": "Second Task"
  },
  {
    "taskDetail": "Enter second task in application."
  },
  {
    "taskList": "Very Important"
  }
]

The problem is that I'm not able to figure out how to group by the id into separate arrays. I've tried several things but without any luck. Any tips or direction to other threads would be awesome. Thanks!

  • 写回答

1条回答 默认 最新

  • donglu0494 2014-04-22 12:02
    关注

    How about something like this:

    while ($row = mysql_fetch_assoc($result))
    {           
        if (!isset($results[$row['id']])) $results[$row['id']] = array();
        $results[$row['id']][$row['name']] = $row['value'] );
    }
    

    Then after you json_encode it you will have all the fields nested in their id

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵