【问题标题】:Create multidimensional array from rows of data从数据行创建多维数组
【发布时间】:2015-07-06 20:25:53
【问题描述】:

我有一个包含项目条目的数据库。每个条目都有一个项目标题、日期戳、输入它的用户和注释。我正在尝试将此数据格式化为 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"
}

}

【问题讨论】:

  • 显示最接近您想要的东西。最好学习如何改进你的代码,而不是复制和粘贴别人会给你的任何东西。

标签: php mysql json mysqli


【解决方案1】:

这应该可以解决问题。您可以将项目名称用作数组键。为了防止字符串键出现在输出数组中,您可以使用 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));

【讨论】:

  • 谢谢,确实有效。我仍然没有完全理解它是如何工作的,或者是什么让我以前的代码不起作用。我很难在网上找到任何有用的东西。对于像这样遍历数组的网站或教程有什么建议吗?
  • @JoshDerocher 我为答案添加了一些很好的解释;希望它会有所帮助。至于对网站的建议,the PHP documentation on arrays 应该会有所帮助。对于教程,我真的没有具体的推荐。
  • 谢谢!这对我来说很清楚。感谢您的帮助:)
【解决方案2】:

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

while ($row = mysqli_fetch_array($result) {
    if (!isset($projects[$row['id']]))
    {
        $projects[$row['id']] = [
            'project_name' => $row['project_name'],
            'entries' => [],
        ];    
    }
    $projects[$row['id']]['entries'][] = [
        'comment' => $row['comment'],    
    ];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2013-01-16
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多