简体   繁体   English

格式化json_encode的数组

[英]Formatting Arrays for 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. 我正在努力地用一些php并将其转换成我想要的json-encode格式,因此我可以使用基因敲除。

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: 我正在尝试使用json_encode将此响应发送到我的网站,如下所示:

[
  {
    "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. 问题是我无法弄清楚如何按ID将ID分组为单独的数组。 I've tried several things but without any luck. 我尝试了几件事,但是没有任何运气。 Any tips or direction to other threads would be awesome. 对其他线程的任何提示或指示都将很棒。 Thanks! 谢谢!

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 然后在json_encode之后,您将把所有字段嵌套在其ID中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM