Skip to content

Instantly share code, notes, and snippets.

@lutsen
Last active August 29, 2015 14:04
Show Gist options
  • Save lutsen/a66ec7d68cb1c9c2d08d to your computer and use it in GitHub Desktop.
Save lutsen/a66ec7d68cb1c9c2d08d to your computer and use it in GitHub Desktop.
Make a Threaded multi level array from a two level array with parent id's. For example comments or a page tree. The class returns an array. Original code from http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/
<?php
// From http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/
// This modified code now returns an array.
class Threaded {
public $parents = array();
public $children = array();
// @param array $threaded_data
function __construct($threaded_data) {
// Each nested array of the $data array needs to have an id and a parent_id key.
foreach ($threaded_data as $data) {
if ($data['parent_id'] === NULL) {
$this->parents[$data['id']][] = $data;
} else {
$this->children[$data['parent_id']][] = $data;
}
}
}
// @param array $data Single data array
// @param int $depth
private function singleThread($data, $depth = 0) {
foreach ($data as $k => $v) {
$data[$k]['depth'] = $depth;
if (isset($this->children[$data[$k]['id']])) {
$data[$k]['children'] = $this->singleThread($this->children[$data[$k]['id']], $depth + 1);
}
}
return $data;
}
public function make() {
$return = array();
foreach ($this->parents as $c) {
$single_thread = $this->singleThread($c);
$return[] = $single_thread[0];
}
return $return;
}
}
// EXAMPLE
$comments = array(
array('id'=>1, 'parent_id'=>NULL, 'text'=>'Parent'),
array('id'=>2, 'parent_id'=>1, 'text'=>'Child'),
array('id'=>3, 'parent_id'=>2, 'text'=>'Child Third level'),
array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'),
array('id'=>5, 'parent_id'=>4, 'text'=>'Second Child'),
array('id'=>6, 'parent_id'=>NULL, 'text'=>'Parent 2'),
array('id'=>7, 'parent_id'=>1, 'text'=>'Child 2'),
array('id'=>8, 'parent_id'=>2, 'text'=>'Child Third level 2'),
array('id'=>9, 'parent_id'=>NULL, 'text'=>'Second Parent 2'),
array('id'=>10,'parent_id'=>4, 'text'=>'Second Child 2')
);
$t = new Threaded($comments);
?>
<pre><?php print_r( $t->make() ); ?></pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment