如何将平面数组排序为多维树

发布于 2024-12-11 08:02:48 字数 500 浏览 0 评论 0原文

我有一个表格,例如

id    catagory      suboff

1     software       0
2     programming    1
3     Testing        1
4     Designing      1
5     Hospital       0
6     Doctor         5
7     Nurses         5
9     Teaching       0
10    php programming 2
11    .net programming 2

如何编写代码以根据 suboff 获取多维数组中的所有这些信息,如下所示,

-software
--programming
---php programming
--- .net programming
--testing
--designing
-hospital 
--doctor
--nurses
-teaching

I have a table like

id    catagory      suboff

1     software       0
2     programming    1
3     Testing        1
4     Designing      1
5     Hospital       0
6     Doctor         5
7     Nurses         5
9     Teaching       0
10    php programming 2
11    .net programming 2

How to write a code to get all these information in a multidimensional array based on the suboff as follows,

-software
--programming
---php programming
--- .net programming
--testing
--designing
-hospital 
--doctor
--nurses
-teaching

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

天涯沦落人 2024-12-18 08:02:48

假设 MySQL 作为您的数据库引擎:

// We'll need two arrays for this
$temp = $result = array();

// Get the data from the DB
$table = mysql_query("SELECT * FROM table");

// Put it into one dimensional array with the row id as the index
while ($row = mysql_fetch_assoc($table)) {
  $temp[$row['id']] = $row;
}

// Loop the 1D array and create the multi-dimensional array
for ($i = 1; isset($temp[$i]); $i++) {
  if ($temp[$i]['suboff'] > 0) {
    // This row has a parent
    if (isset($temp[$temp[$i]['suboff']])) {
      // The parent row exists, add this row to the 'children' key of the parent
      $temp[$temp[$i]['suboff']]['children'][] =& $temp[$i];
    } else {
      // The parent row doesn't exist - handle that case here
      // For the purposes of this example, we'll treat it as a root node
      $result[] =& $temp[$i];
    }
  } else {
    // This row is a root node
    $result[] =& $temp[$i];
  }
}

// unset the 1D array
unset($temp);

// Here is the result
print_r($result);

使用 引用 来完成这样的工作。

Assuming MySQL as your DB engine:

// We'll need two arrays for this
$temp = $result = array();

// Get the data from the DB
$table = mysql_query("SELECT * FROM table");

// Put it into one dimensional array with the row id as the index
while ($row = mysql_fetch_assoc($table)) {
  $temp[$row['id']] = $row;
}

// Loop the 1D array and create the multi-dimensional array
for ($i = 1; isset($temp[$i]); $i++) {
  if ($temp[$i]['suboff'] > 0) {
    // This row has a parent
    if (isset($temp[$temp[$i]['suboff']])) {
      // The parent row exists, add this row to the 'children' key of the parent
      $temp[$temp[$i]['suboff']]['children'][] =& $temp[$i];
    } else {
      // The parent row doesn't exist - handle that case here
      // For the purposes of this example, we'll treat it as a root node
      $result[] =& $temp[$i];
    }
  } else {
    // This row is a root node
    $result[] =& $temp[$i];
  }
}

// unset the 1D array
unset($temp);

// Here is the result
print_r($result);

Use references for a job like this.

夏の忆 2024-12-18 08:02:48

演示:http://ideone.com/vk4po

$array = array(
array('1','software','0'),
array('2','programming','1'),
array('3','Testing','1'),
array('4','Designing','1'),
array('5','Hospital','0'),
array('6','Doctor','5'),
array('7','Nurses','5'),
array('9','Teaching','0'),
array('10','php programming','2'),
array('11','.net programming','2')
);

function menu_sort($results, $master = 0)
{

    $open = array();
    $return = NULL;

    foreach($results as $result)
    {
        if($result[2] == $master){

            if(!$open){
                $return .= '<ul>';
                $open = true;
            }

            $return .= '<li>'.$result[1];

            $return .= menu_sort($results, $result[0]);
            $return .= '</li>';

        }
    }

    if($open)
        $return .= '</ul>';

    return $return;

}

echo menu_sort($array);

结果...

<前><代码>软件
编程
PHP编程
.net 编程
测试
设计
医院
医生
护士
教学

Demo: http://ideone.com/vk4po

$array = array(
array('1','software','0'),
array('2','programming','1'),
array('3','Testing','1'),
array('4','Designing','1'),
array('5','Hospital','0'),
array('6','Doctor','5'),
array('7','Nurses','5'),
array('9','Teaching','0'),
array('10','php programming','2'),
array('11','.net programming','2')
);

function menu_sort($results, $master = 0)
{

    $open = array();
    $return = NULL;

    foreach($results as $result)
    {
        if($result[2] == $master){

            if(!$open){
                $return .= '<ul>';
                $open = true;
            }

            $return .= '<li>'.$result[1];

            $return .= menu_sort($results, $result[0]);
            $return .= '</li>';

        }
    }

    if($open)
        $return .= '</ul>';

    return $return;

}

echo menu_sort($array);

Result...

software
    programming
        php programming
        .net programming
    Testing
    Designing
Hospital
    Doctor
    Nurses
Teaching
喜爱纠缠 2024-12-18 08:02:48

我的做法是:

  1. 首先您需要解析该表。我想你可以自己做;如果没有,谷歌“正则表达式”,它们是你的朋友。

  2. 您正在使用的数据结构是经典的。您将需要两个数组来使用它。首先是一个节点数组,$nodes,其中键是节点 ID,值是节点名称,以及 $links,其中每个键是父节点,每个value 是一个子数组($links[$id][] = $suboff 对于每个元素就足够了)。

  3. 现在你必须递归地下降你拥有的树。您引入一个具有如下签名的函数:

    函数 print_node( $nodeID, $level = 1 )
    

    此函数应该使用 $level 填充破折号打印节点本身(存储在 $nodes 中的信息),并调用自身来渲染所有子节点。它们将依次渲染所有子节点等。您只需为顶级节点调用此函数即可。

The way I would do that:

  1. First you need to parse this table. I assume you can do it yourself; if not, Google "regular expressions", they are your friends.

  2. The data structure you are working with is a classical tree. You will need two arrays to work with it. First is an array of nodes, $nodes, where the keys are the node IDs and values are node names, and $links, where each key is a parent node and each value is an array of children ($links[$id][] = $suboff for each element would suffice).

  3. Now you have to recursively descent the tree you have. You introduce a function with a signature like this:

    function print_node( $nodeID, $level = 1 )
    

    This function should print the node itself (info stored in $nodes) with $level padding dashes and call itself to render all children nodes. They will in turn render all their subnodes, etc. You just have to call this function for top-level nodes.

会发光的星星闪亮亮i 2024-12-18 08:02:48

此类将平面类别数组转换为结构化树数组:

<?php

/**
 * Creates a structured tree out of a flat category list
 */
class CategoryTree {

  /**
   *
   * @var array
   */
  protected $categories = array();

  /**
   *
   * @var array
   */
  protected $tree = array();

  /**
   * Default constructor
   * @param array $categories 
   */
  function __construct(array $categories) {
    $this->categories = $categories;
  }

  /**
   * Process a subtree
   * @param array $categories
   * @param integer $parentId
   * @return array 
   */
  protected function getSubtree(array $categories, $parentId = 0) {
    $tree = array();

    foreach($categories as $category) {
      if($category['suboff'] == $parentId) {
        $tree[$category['id']] = $category;
        $tree[$category['id']]['children'] = $this->getSubtree($categories, $category['id']);
      }
    }

    return $tree;
  }

  /**
   * Get the category tree as structured array
   * @return array 
   */
  public function getTree() {
    if(empty($this->tree)) {
      $this->tree = $this->getSubtree($this->categories, 0);
    }
    return $this->tree;
  }

  /**
   * Get the category tree as string representation
   * @return string
   */
  public function __toString() {
    return "<pre>" . print_r($this->getTree(), true) . "</pre>";
  }

}


// Now, use the class with the givven data:

$categories = array(
  array(
    'id' => 1,
    'category' => 'software',
    'suboff' => 0
  ),
  array(
    'id' => 2,
    'category' => 'programming',
    'suboff' => 1
  ),
  array(
    'id' => 3,
    'category' => 'Testing',
    'suboff' => 1
  ),
  array(
    'id' => 4,
    'category' => 'Designing',
    'suboff' => 1
  ),
  array(
    'id' => 5,
    'category' => 'Hospital',
    'suboff' => 0
  ),
  array(
    'id' => 6,
    'category' => 'Doctor',
    'suboff' => 5
  ),
  array(
    'id' => 7,
    'category' => 'Nurses',
    'suboff' => 5
  ),
  array(
    'id' => 9,
    'category' => 'Teaching',
    'suboff' => 0
  ),
  array(
    'id' => 10,
    'category' => 'php programming',
    'suboff' => 2
  ),
  array(
    'id' => 11,
    'category' => '.net programming',
    'suboff' => 2
  )
);

$myTree = new CategoryTree($categories);
echo $myTree;

?>

This class converst a flat category array into a structured tree array:

<?php

/**
 * Creates a structured tree out of a flat category list
 */
class CategoryTree {

  /**
   *
   * @var array
   */
  protected $categories = array();

  /**
   *
   * @var array
   */
  protected $tree = array();

  /**
   * Default constructor
   * @param array $categories 
   */
  function __construct(array $categories) {
    $this->categories = $categories;
  }

  /**
   * Process a subtree
   * @param array $categories
   * @param integer $parentId
   * @return array 
   */
  protected function getSubtree(array $categories, $parentId = 0) {
    $tree = array();

    foreach($categories as $category) {
      if($category['suboff'] == $parentId) {
        $tree[$category['id']] = $category;
        $tree[$category['id']]['children'] = $this->getSubtree($categories, $category['id']);
      }
    }

    return $tree;
  }

  /**
   * Get the category tree as structured array
   * @return array 
   */
  public function getTree() {
    if(empty($this->tree)) {
      $this->tree = $this->getSubtree($this->categories, 0);
    }
    return $this->tree;
  }

  /**
   * Get the category tree as string representation
   * @return string
   */
  public function __toString() {
    return "<pre>" . print_r($this->getTree(), true) . "</pre>";
  }

}


// Now, use the class with the givven data:

$categories = array(
  array(
    'id' => 1,
    'category' => 'software',
    'suboff' => 0
  ),
  array(
    'id' => 2,
    'category' => 'programming',
    'suboff' => 1
  ),
  array(
    'id' => 3,
    'category' => 'Testing',
    'suboff' => 1
  ),
  array(
    'id' => 4,
    'category' => 'Designing',
    'suboff' => 1
  ),
  array(
    'id' => 5,
    'category' => 'Hospital',
    'suboff' => 0
  ),
  array(
    'id' => 6,
    'category' => 'Doctor',
    'suboff' => 5
  ),
  array(
    'id' => 7,
    'category' => 'Nurses',
    'suboff' => 5
  ),
  array(
    'id' => 9,
    'category' => 'Teaching',
    'suboff' => 0
  ),
  array(
    'id' => 10,
    'category' => 'php programming',
    'suboff' => 2
  ),
  array(
    'id' => 11,
    'category' => '.net programming',
    'suboff' => 2
  )
);

$myTree = new CategoryTree($categories);
echo $myTree;

?>
完美的未来在梦里 2024-12-18 08:02:48

这是我刚刚为我的应用程序编写的内容,它就像一个魅力:)

$array = [
    'i' => ['key' => 'i', 'name' => 'php programming', 'parent' => 'b'], 
    'g' => ['key' => 'g', 'name' => 'Nurses', 'parent' => 'e'],
    'j' => ['key' => 'j', 'name' => '.net programming', 'parent' => 'b'], 
    'b' => ['key' => 'b', 'name' => 'programming', 'parent' => 'a'],
    'a' => ['key' => 'a', 'name' => 'software', 'parent' => 'asd'],
    'c' => ['key' => 'c', 'name' => 'Testing', 'parent' => 'a'], 
    'd' => ['key' => 'd', 'name' => 'Designing', 'parent' => 'a'], 
    'e' => ['key' => 'e', 'name' => 'Hospital', 'parent' => 'asd'],  
    'f' => ['key' => 'f', 'name' => 'Doctor', 'parent' => 'e'], 
    'h' => ['key' => 'h', 'name' => 'Teaching'],  
];

function getAsTree(array &$array)
{
    foreach ($array as $key => $item) {
        if (isset($item['parent']) && isset($array[$item['parent']])) {
            $array[$item['parent']]['children'][] = $item;
            unset($array[$key]);
            return getAsTree($array);
        }
    }

    return $array;
}

这是结果:

--- a:软件
------ b:编程
--------- 一:php编程
--------- j:.net 编程
------ c:测试
------ d:设计
--- e:医院
------ g:护士
------ f:医生
--- h:教学

This is what I just wrote for my app, and it works like a charm :)

$array = [
    'i' => ['key' => 'i', 'name' => 'php programming', 'parent' => 'b'], 
    'g' => ['key' => 'g', 'name' => 'Nurses', 'parent' => 'e'],
    'j' => ['key' => 'j', 'name' => '.net programming', 'parent' => 'b'], 
    'b' => ['key' => 'b', 'name' => 'programming', 'parent' => 'a'],
    'a' => ['key' => 'a', 'name' => 'software', 'parent' => 'asd'],
    'c' => ['key' => 'c', 'name' => 'Testing', 'parent' => 'a'], 
    'd' => ['key' => 'd', 'name' => 'Designing', 'parent' => 'a'], 
    'e' => ['key' => 'e', 'name' => 'Hospital', 'parent' => 'asd'],  
    'f' => ['key' => 'f', 'name' => 'Doctor', 'parent' => 'e'], 
    'h' => ['key' => 'h', 'name' => 'Teaching'],  
];

function getAsTree(array &$array)
{
    foreach ($array as $key => $item) {
        if (isset($item['parent']) && isset($array[$item['parent']])) {
            $array[$item['parent']]['children'][] = $item;
            unset($array[$key]);
            return getAsTree($array);
        }
    }

    return $array;
}

And here is the result:

--- a: software
------ b: programming
--------- i: php programming
--------- j: .net programming
------ c: Testing
------ d: Designing
--- e: Hospital
------ g: Nurses
------ f: Doctor
--- h: Teaching
过气美图社 2024-12-18 08:02:48

恕我直言,逻辑是:

  1. 获取所有根元素(软件、医院等)
  2. Foreach 根获取子元素(对于您将进行编程、测试和设计的软件)
  3. 将子元素添加为子数组
  4. 在您刚刚添加的子数组上递归循环

IMHO the logic is:

  1. Get all the roots element (software, hospital and so on)
  2. Foreach root take the subelement(s) (for the software you'll take programming, testing and designing)
  3. Add the subelement(s) as subarray
  4. Loop recursively on the subarray(s) you just add
居里长安 2024-12-18 08:02:48

您需要将整个表读入内存并将其转换为一棵树,其中每个节点都可以用其相应的 ID 号进行标识。然后对树进行预序遍历并将其打印出来。

You'll want to read the whole table into memory and turn it into a tree where each node can be identified with its corresponding id number. Then do a pre-order traversal of the tree to print it out.

浮华 2024-12-18 08:02:48

在 PHP wenn 中,我从数据库获取数据:

"SELECT* FROM Table WHERE suboff LIKE 0"
foreach(item..)
   "SELECT* FROM Table WHERE suboff LIKE item.ID"
       foreach(item2..)
          $result[item][item2]

In PHP wenn i get the data from a Database:

"SELECT* FROM Table WHERE suboff LIKE 0"
foreach(item..)
   "SELECT* FROM Table WHERE suboff LIKE item.ID"
       foreach(item2..)
          $result[item][item2]
小梨窩很甜 2024-12-18 08:02:48

这是一种不同的方法,应该很容易理解。它要求您将表按 suboff 排序,即

SELECT * FROM table ORDER BY suboff

假设结果存储在 $table 中,您可以使用这个非常简洁的 php 代码:

// this will hold the result
$tree = array();
// used to find an entry using its id
$lookup = array();
foreach($table as $row){
  if($row['suboff'] === 0){
    // this has no parent, add it at base level
    $tree[$row['category']] = array();
    // store a reference
    $lookup[$row['id']] =& $tree[$row['category']];
  }else{
    // find the right parent, add the category
    $lookup[$row['suboff']][$row['category']] = array();
    // store a reference
    $lookup[$row['id']] =& $lookup[$row['suboff']][$row['category']];
  }
}

Here is a different approach that should be very easy to understand. It requires you to have the table ordered by suboff, i.e.

SELECT * FROM table ORDER BY suboff

Assuming the result is stored in $table, you can use this very concise php code:

// this will hold the result
$tree = array();
// used to find an entry using its id
$lookup = array();
foreach($table as $row){
  if($row['suboff'] === 0){
    // this has no parent, add it at base level
    $tree[$row['category']] = array();
    // store a reference
    $lookup[$row['id']] =& $tree[$row['category']];
  }else{
    // find the right parent, add the category
    $lookup[$row['suboff']][$row['category']] = array();
    // store a reference
    $lookup[$row['id']] =& $lookup[$row['suboff']][$row['category']];
  }
}
云巢 2024-12-18 08:02:48

这个解决方案对我来说效果很好。

$array = array(
    array('1','software','0'),
    array('2','programming','1'),
    array('3','Testing','1'),
    array('4','Designing','1'),
    array('5','Hospital','0'),
    array('6','Doctor','5'),
    array('7','Nurses','5'),
    array('9','Teaching','0'),
    array('10','php programming','2'),
    array('11','.net programming','2')
);

$newArray = getTree($array);

function getTree( $rows, $suboff = 0) {

    $return = array();

    foreach($rows as $row) {

        if($row[2] == $suboff){

            $newrow = $row;

            $subs = $this->getTree($rows, $row[0]);

            if ( !empty($subs) ) {
                $newrow['subs'] = $subs;
            }

            $return[] = $newrow;

        }
    }

    return $return;

}

This solution works fine for me.

$array = array(
    array('1','software','0'),
    array('2','programming','1'),
    array('3','Testing','1'),
    array('4','Designing','1'),
    array('5','Hospital','0'),
    array('6','Doctor','5'),
    array('7','Nurses','5'),
    array('9','Teaching','0'),
    array('10','php programming','2'),
    array('11','.net programming','2')
);

$newArray = getTree($array);

function getTree( $rows, $suboff = 0) {

    $return = array();

    foreach($rows as $row) {

        if($row[2] == $suboff){

            $newrow = $row;

            $subs = $this->getTree($rows, $row[0]);

            if ( !empty($subs) ) {
                $newrow['subs'] = $subs;
            }

            $return[] = $newrow;

        }
    }

    return $return;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文