Grouping/Ordering Items in PHP Object Array

  arrays, json, php

I have a sitemap that I’m trying to group by URL and stack them based on URL. Here is the sitemap https://www.sitecentre.com.au/sitemap

Basically, I need this to be dynamic. I can make this easily by doing a case, or if statements, like I’ve done on the Blog section, but I need it dynamic. It needs to look like this:

<li>Web Design
    <ul>
        <li>Nested in Web Design</li>
        <li>Nested in Web Design</li>
    </ul>
</li>

All based on the URL. the URL is /design then the nested would be design/nested

Then the next group would be like branding and nested on branding so it’s all organised and laid out perfectly, then alphabetically ordered based on something else.

Here is our current PHP:

<?php
    $pages = json_decode(file_get_contents('data/pages.json'));

    foreach ($pages as $data){
        foreach ($data as $key => $values){
            if ($values->status === '1' && $values->visible === '1' && $values->slug !== 'home'){

                if ($values->slug !== 'blog'){
                    echo '<li><a href="{{domain}}/' . $values->slug . '" title="' . $values->heading . '">' . $values->heading . '</a> - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
                } else {
                    // Get the latest blogs
                    $blogs = json_decode(file_get_contents('data/blogs.json'));

                    echo '<li><a href="{{domain}}/' . $values->slug . '" title="' . $values->heading . '">' . $values->heading . '</a> - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '';
                    echo '<ul>';

                    foreach ($blogs as $data){
                        foreach ($data as $key => $values){
                            if ($values->status === '1' && $values->visible === '1'){
                                echo '<li><a href="{{domain}}/' . $values->slug . '" title="' . $values->heading . '">' . $values->heading . '</a> - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
                            }
                        }
                    }
                    echo '</li></ul>';
                }
            }
        }
    }
?>

It clearly needs a bit of work in order to make this work, but I cannot for the life of me work out where to start.

Source: Ask PHP

LEAVE A COMMENT