Tips on creating a recursive function based on depth levels

Function in need of completion:

 public static function f($rows)
       {
           $str = '<ul>';
           $level = 1;
           foreach($rows as $row)
           {
               if($row['section_level'] > $level)
               {
                   $level = $row['section_level'];
                   // Need to implement recursive function call here
               }
               else
               {
                   $str .= '<li><a href="#">'.$row['username'].'</a></li>';
               }
           }
           $str .= '</ul>';
           return $str;
       }

The provided array structure:

array (

   array(

     ['name'] => 'test1',
     ['level'] => 1

   },
   array(

     ['name'] => 'test2',
     ['level'] => 2

   },

   array(

     ['name'] => 'test3',
     ['level'] => 2

   },
   array(

     ['name'] => 'test4',
     ['level'] => 3

   },
   array(

     ['name'] => 'test5',
     ['level'] => 3

   },
   array(

     ['name'] => 'test6',
     ['level'] => 3

   },
   array(

     ['name'] => 'test7',
     ['level'] => 3

   },



)

Please assist in completing the function to render the array based on levels, with each level being enclosed in a <ul>, resulting in a hierarchy like this:

<ul>
  <li>
  <a href="#">level1</a>
    <ul>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
    </ul>
  </li>
  <li>
  <a href="#">level1</a>
    <ul>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
      <li><a href="#">level2</a></li>
    </ul>
  </li>
</ul>

Answer №1

Recursion focuses on building a tree-like data structure.

In this context, the depth of the structure is not as crucial as the parent-child relationships.

This implies that each array element must contain at least two values, for example:

[ 'id' => 1, 'parent' => null ],
[ 'id' => 2, 'parent' => 1 ],
[ 'id' => 3, 'parent' => 1 ],
[ 'id' => 4, 'parent' => 2 ],
....

Once your data array is ready, you can utilize to process the array and obtain a structured output.

Then, utilizing the Recursion function, you can generate HTML like so:

function display( $ary ){
    echo '<ul>';
    foreach($ary as $data){
        echo '<li>';
        echo $data['html'];
        if( sizeof( $data['node'] ) ){
            display( $ary );
        }
        echo '</li>';
    }
    echo '</ul>';
}

The provided solution for nested structures may not be ideal:

function f($rows)
{
    $str = '';
    $level = 0;
    $first_li_mode = true;
    foreach ($rows as $row) {
        if ($level > $row['level']) {
            $str .= '</li></ul>' . "\n";
            $str .= '</li><li><a href="#">' . $row['name'] . '</a>' . "\n";
            $first_li_mode = true;
        } elseif ($row['level'] > $level) {
            $str .= '<ul><li><a href="#">' . $row['name'] . '</a>' . "\n";
            $first_li_mode = false;
            ;
        } else {
            if (!$first_li_mode) {
                $str .= '</li>' . "\n";
            } else {
                $first_li_mode = false;
            }
            $str .= '<li><a href="#">' . $row['name'] . '</a>' . "\n";
        }

        $level = $row['level'];
    }
    while ($level > 0) {
        $str .= '</li></ul>' . "\n";
        $level--;
    }
    return $str;
}


$qrr = array(
    array('name' => 'test1', 'level' => 1),
    array('name' => 'test2', 'level' => 2),
    array('name' => 'test3', 'level' => 2),
    array('name' => 'test4', 'level' => 3),
    array('name' => 'test5', 'level' => 3),
    array('name' => 'test6', 'level' => 3),
    array('name' => 'test7', 'level' => 3),
    array('name' => 'test8', 'level' => 2),
    array('name' => 'test9', 'level' => 1),
);

echo f($qrr);

Answer №2

Have you considered using a nested loop?

<?php 
function displayNestedArray($rows)
       {
           $nestedList = '';
           $level = 1;
           $i = 1;
           foreach($rows as $row)
           { 

         $nestedList .="<ul><li>".$i;


            $nestedList .="<ul><li>".$row['name']."</li><li>".$row['level']."</li></ul>";                   

              $nestedList .="</li></ul>";
              $i++;
           }
           $nestedList .= '</ul>';
           return $nestedList;
       }

$sampleArray = array(
   array(
    'name' => 'test1',
     'level' => 1
   ),
   array(

     'name' => 'test2',
     'level'=> 2
   ),

   array(

     'name' => 'test3',
     'level' => 2

   ),
   array(

     'name' => 'test4',
     'level'=> 3

  ),
   array(

     'name' => 'test5',
     'level' => 3

   ),
   array(

     'name' => 'test6',
     'level'=> 3

   ),
   array(

     'name' => 'test7',
     'level' => 3

   ),
);

echo displayNestedArray($sampleArray);
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The class [AdminController] being targeted does not exist

https://i.sstatic.net/r6c7q.pngI encountered an issue where a user is redirected from login to the admin page (e.g. ), and a 403 error should be triggered if the user is not logged in as an admin. Interestingly, even the admin experiences the same error. ...

Every initial test with Protractor ends in failure

Here are the versions I am currently using: protractor v5.1.2 chromedriver v2.33 node v6.11.4 npm 3.10.10 selenium-webdriver v3.0.1 I am a beginner with protractor and I am attempting to run the provided test natively included in protractor. The test scr ...

Issue with Bootstrap 4 Video Embed not autoplaying within iframe

Is it possible to make an embedded Youtube video autoplay using Bootstrap 4? I have searched the documentation but haven't found the answer. Most sources online suggest adding 'autoplay' in the iframe tag, but that doesn't seem to work ...

Eliminate the hover effect from every element

Is there a method in CSS or Javascript that allows me to eliminate the hover effect on all elements? I am specifically looking for a solution that will disable the hover effect on mobile devices while keeping it intact on desktop. I attempted using pointer ...

Problems Arising with Bootstrap Media Queries on Smaller Tablets in Landscape View

I am currently using Bootstrap's standard media queries for my project and they are working perfectly, except for small tablets in landscape mode. I have included an image to demonstrate this issue. The problem seems to arise from the custom CSS that ...

Activate the angular function

In the controller below, there is a function that should be triggered when the link is clicked: <a id="1" href="" name="xxx" ng-click="searchall(id)">sample link</a> ng.controller('SearchResultController', ['$scope', &apos ...

Generate various routes and subroutes from an array

I need to create routes for an array of items, each with its own main page and nested pages. Here is an example structure: myapp.com/[item] (main item page) myapp.com/[item]/about (about item page) myapp.com/[item]/faq (faq item page) My goal is to itera ...

What is the process for utilizing an API link instead of a local JSON file in React Table?

I have a query that may seem trivial, but I haven't been able to locate an answer elsewhere. Instead of using the code below with a local file (MOCK_DATA.json) to render a table, I want to retrieve data from an API. What modifications should I make? ...

Unusual margin that demands attention!

I'm currently in the process of designing a website and have just started working on the header section. However, I've encountered an issue where there is an unexpected 28px margin at the top. Upon inspecting the code, I found the culprit: medi ...

Element sticking and bouncing

I'm currently facing an issue with Sticky-kit where one of my elements jumps when it reaches the bottom of its parent div. Below is the code snippet: <div class="wrapper"> <div id="bg"> <div id="text"> Lorem ipsum dolor sit a ...

Filtering date ranges in two columns of Datatables

I am working on a table that contains two date columns. Currently, I have implemented a date range filter for one column (aData[3]) using the following code: $.fn.dataTableExt.afnFiltering.push( function(oSettings, aData, iDataIndex) { var dat ...

What is the best way to enable sorting for a dynamically loaded UL in a JQuery UI dialog using AJAX?

I am facing an issue with loading a UL in the background and displaying it in a dialog for sorting. I am new to JQuery/JQuery UI and struggling to find a solution through Google search. This is my current code: $(document).on('click','a.pri ...

What is the best way to open an HTML file with Python without restrictions?

My HTML file is quite large, containing 4,574 words and 57,718 characters. However, when I try to read it using the .read() command, it only displays 3,004 words and 39,248 characters when I export it. Is there a way to read and export it without any lim ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

What is the best way to create a feature in Vue that filters options in real-time as we type into a

In my Vue application, I am trying to implement dynamic filtering for the options in a search box as the user types. Currently, the search box displays the entire list of options without any filtering happening even when the user is typing. <el-form-it ...

Using Wordpress with Gravity Forms Ajax and Swup JS for dynamic form submissions

For page transitions and AJAX content changes, I have implemented swup.js. However, Gravity forms is not properly handling the AJAX request and the form stops working after transitioning. To reinitialize my scripts upon page load, I am using the following ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

Accessing individual .env files defined in the package.json

"begin:development": "set NODE_ENV=development&&nodemon ./bin/www", "begin:testing": "set NODE_ENV=testing&&nodemon ./bin/www", I am managing two unique .env files named dev.env and test.env. My goal is to utilize dev.env when running npm ...

Guide to horizontally aligning a div with a dynamic width in the center

After extensive research, I discovered that setting a width allows you to center a div using margin: 0 auto along with left: 0;, right: 0, and position: absolute. However, all the examples I found had a specified width. In my specific case, I need to cent ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...