test1 - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of test1.php
- <?php
- $datas = array(
- array('id' => 1, 'parent_id' => 0, 'name' => 'Parent 1'),
- array('id' => 2, 'parent_id' => 1, 'name' => 'Child 1.1'),
- array('id' => 3, 'parent_id' => 2, 'name' => 'Child with child 1.1.1'),
- array('id' => 4, 'parent_id' => 2, 'name' => 'Child with child 1.1.2'),
- array('id' => 5, 'parent_id' => 4, 'name' => 'Child with child of child 1.1.2.1'),
- array('id' => 5, 'parent_id' => 1, 'name' => 'Child 1.2'),
- array('id' => 6, 'parent_id' => 5, 'name' => 'Child with child 1.2.1'),
- array('id' => 7, 'parent_id' => 5, 'name' => 'Child with child 1.2.2'),
- array('id' => 8, 'parent_id' => 5, 'name' => 'Child with child 1.2.3'),
- array('id' => 9, 'parent_id' => 0, 'name' => 'Parent 2'),
- array('id' => 10, 'parent_id' => 9, 'name' => 'Child 2.1'),
- array('id' => 11, 'parent_id' => 9, 'name' => 'Child 2.2'),
- array('id' => 12, 'parent_id' => 11, 'name' => 'Child with child 2.2.1'),
- array('id' => 13, 'parent_id' => 11, 'name' => 'Child with child 2.2.2'),
- array('id' => 14, 'parent_id' => 0, 'name' => 'Parent 3'),
- array('id' => 15, 'parent_id' => 14, 'name' => 'Child 3.1'),
- array('id' => 16, 'parent_id' => 15, 'name' => 'Child with child 3.1.1'),
- array('id' => 17, 'parent_id' => 15, 'name' => 'Child with child 3.1.2')
- );
- function generatePageTree($datas, $parent = 0, $depth = 0) {
- $ni=count($datas);
- if($ni === 0 || $depth > 1000) return ''; // Make sure not to have an endless recursion
- $tree = '<ul>';
- for($i=0; $i < $ni; $i++){
- if($datas[$i]['parent_id'] == $parent){
- $tree .= '<li>';
- $tree .= $datas[$i]['name'];
- $tree .= generatePageTree($datas, $datas[$i]['id'], $depth+1);
- $tree .= '</li><br/>';
- }
- }
- $tree .= '</ul>';
- return $tree;
- }
- //echo(generatePageTree($datas));
- var_dump(generatePageTree($datas));
File Description
- test1
- PHP Code
- 22 Aug-2022
- 1.85 Kb
You can Share it:
Latest PHP Pastes