从数据行创建多维数组

时间:2015-07-06 20:25:53

标签: php mysql json mysqli

我有一个包含项目条目的数据库。每个条目都有一个项目标题,日期戳,输入它的用户和注释。我正在尝试将此数据格式化为报告和图表的JSON。

我想为每个项目名称添加一个数组,并在该数组中为每个项目添加一个数组。

我尝试了几种方法,但我还没有多少运气。

if ($result = $mysqli->query("SELECT * FROM project_entries"))
    // WHERE WEEK(date) = WEEK(current_date) ORDER BY project_name
    {
    while ($row = mysqli_fetch_array($result)) {
        $entry_array = array();
        $row_array['project_name'] = $row['project_name'];
        $comment = $row['comment'];
        $entry = array (
            'comment' => $comment,
            );
        $row_array['entries'] = $entry;
        if ( !in_array($row['project_name'], $projects, false ))
            {
                array_push($projects, $row_array);
            }
    }
}

输出:

[
  {
    "project_name": "Logo Design",
    "entries": {
      "comment": "Worked on a thing"
    }
  },
  {
    "project_name": "Logo Design",
    "entries": {
      "comment": "Created some stuff"
    }
  },

虽然我想:

  {
"project_name": "Logo Design",
"entries": {
  "comment": "Worked on a thing",
  "comment": "Created some stuff"
}

}

2 个答案:

答案 0 :(得分:0)

也许是这样的? 使用项目ID来构建目标数组。

class[Pp_package_manager] => Class[User_manager]

答案 1 :(得分:0)

这应该可以解决问题。您可以将项目名称用作数组键。为了防止字符串键出现在输出数组中,可以使用array_values将它们转换为数字键。

$projects = array();
while ($row = mysqli_fetch_array($result)) {
    $projects[$row['project_name']]['project_name'] = $row['project_name'];
    $projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
}
echo json_encode(array_values($projects));

您之前的代码出了什么问题:

if ($result = $mysqli->query("SELECT * FROM project_entries")) {
    while ($row = mysqli_fetch_array($result)) {
        $entry_array = array(); // This does not appear to be used

        // With each iteration of the while loop, you create a new array of
        // project information (project name and entries array with one comment)
        $row_array['project_name'] = $row['project_name'];        
        $comment = $row['comment'];        
        $entry = array ('comment' => $comment);
        $row_array['entries'] = $entry;

        // The $projects array is an array of arrays, but $row['project_name'] is
        // a string. Checking if this string is in an array of arrays will always
        // be false, so the array_push should always execute.
        if (!in_array($row['project_name'], $projects, false )) {
                // Adds the new project array to the projects array
                array_push($projects, $row_array);
        }
        // This is not producing what you want because you are adding a new
        // array to $row_array each time the loop runs
    }
}

为什么我建议的代码有效:

$projects = array(); // Empty array to hold all the projects
while ($row = mysqli_fetch_array($result)) {
    // Using the project name from the database as an array key in the array we are 
    // constructing keeps the projects unique in that array.

    // The first time a new project name occurs, this will create a new sub-array
    // within $projects with project_name => the new project name. This value will
    // be overwritten on subsequent occurrences of the same project name.
    $projects[$row['project_name']]['project_name'] = $row['project_name'];

    // For each iteration, this will add a comment to the 'entries' array in the
    // project array with the key $row['project_name'].
    $projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);

    // For example, with the first iteration of the array we create the following:
    //
    // $projects['Logo Design'][
    //        'project_name' =>'Logo Design', 
    //        'entries' => [0 => ['comment' => 'Worked on a thing'] ] ]
    //
    // with the second iteration, the project name is overwritten (with same project name)
    // and another comment array is added to the entries array
    //
    // $projects['Logo Design'][
    //        'project_name' =>'Logo Design', 
    //        'entries' => [0 => ['comment' => 'Worked on a thing'],
    //                      1 => ['comment' => 'Created some stuff'] ] ]
}
// If you just did echo json_encode($projects), you would not get the format you want,
// because of the string keys. Try it without the array_values() to see what I mean.
echo json_encode(array_values($projects));