php - Sql 多链表

标签 php sql linked-list iteration

我正在尝试显示可以执行某些步骤的顺序。有些步骤可以同时执行,而另一些步骤则必须按特定顺序执行。我已经将数据存储在 SQL 表中,只是希望能够将其提取到 PHP 数组或其他内容中,以便我可以将其打印出来。

数据存储在1个sql表中,有2个字段。第一个是 stat(这是该 block 的编号),第二个是 prereq,它标识前一个 block (这可能是其他一些统计数据)。如果 prereq 字段为空,则这是起点。当没有其他行时即为结束点。

第一个例子:

status_number    prereq
-------------    -------
3                NULL
4                3
5                4
6                4
7                5
7                6
8                7

从概念上看是这样的:

我正在考虑直观地打印它,首先我想将数据放入 PHP 数组中,并使用嵌套数组来垂直放置 2 个统计数据(在本例中为 5 和 6)。因此,该数组将如下所示:(3,4,(5,6),7,8)。我怎样才能将数据转化为这种形式?感谢您的帮助!

最佳答案

我认为这应该可行,尽管我必须承认我还没有测试过它:

# get the data - let the DB handle the ordering
$sql = "SELECT status_number,prereq FROM t ORDER BY prereq, status_number"
$res = mysql_query($sql);

# initialize pre-loop stuff
$status_array = array();
$prev_prereq = '';

# loop through the results
while ($row = mysql_fetch_assoc($res))
{
  # check if the prereq is the same as the previous result, and if so...
  if ($prev_prereq == $row['prereq'])
  {
    # look at the last element in the array
    end($status_array);
    $lastIndex = key($status_array);

    # if it's not an array
    if (! is_array($status_array[lastIndex]))
    {
      #  make it one that contains the value that was in that spot
      $v = $status_array[lastIndex]
      $status_array[lastIndex] = array();
      status_array[$lastIndex][] = $v;
    }

    # then append the status to that array
    status_array[$lastIndex][] = $row['status_number'];

  } else
  # just append the latest status the the end of the status array
  {
    $status_array[] = $row['status_number'];
    $prev_prereq = $row['prereq'];
  }
}

关于php - Sql 多链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5188952/

相关文章:

php - 如何使用 AJAX 使用查询的最后一个 ID 进行查询?

mysql - 如何在使用 select 的查询中仅获取具有重复值的列中的最后一个结果?

SQL 警告代码 : -1100, SQLState:02000

php - 无法添加或更新子行: a foreign key constraint fails(Foreign key issue in mysql)

linked-list - 创建一个包含头节点和尾节点的链表

Java 如何检查链表是否有重复条目

php - 我应该为每个项目下载 Laravel 吗?

php - 如何在 PHP 中运行 MySQL 查询并将数据发送回浏览器?

php - 使用 mysql/php 获取数据的安全方法

c - 如何使用 LIST_FOREACH_SAFE?