PHP - Convert Adjacency set to nested JSON

Who is this article for?

Anyone looking for how to convert an adjacency set to a nested JSON response. Different types of data can be stored as adjacency set e.x. Menu items, any kind of hierarchy, etc.

In this article, I’m going to walk through on a couple of algorithms written in PHP.

Before You Begin

We will be utilizing the data definition and structure from this article - MySQL – Adjacency List Model For Hierarchical Data Using CTE. You can refer to this post to create the MySQL Table and populate data.

Method 1

Method 2

Output

Performance Comparision

For performance comparison, I am going to use blackfire.io. We will be ignoring the performance of all other components like MySQL except for transformTree(). To get more accurate results, I am going to use several sample size, in this case, I used  10.

Method 1

Method 2

Basic Result

# EXECUTION TIME I/O WAIT TIME CPU PEAK MEMORY
Method 1 734 µs 376 µs 358 µs 44.2 kB
Method 2 762 µs 392 µs 371 µs 44.8 kB

Recursive Calls for transformTree()

# TOTAL DB RECORDS CALLS FOR transformTree()
Method 1 14 15
Method 2 14 4

Full Result of Method 1 Full Result of Method 2

Conclusion

As you can see both Method 1 and Method 2 generates the same output. These can be used with any type of dataset. It performs recursive operations and produces output for any depth of data.

Although, we don't really see the benefit of using Method 2 over Method 1 as the data set used is very small. The difference in performance is almost similar for small dataset.

But, I would strongly recommend using Method 2, as this method is far more superior and faster.

In my next article, we will dive deep into comparing the performance of these two methods.

Posted in JSON, PHP, BLOG
Akki K

Akki

Experienced Backend Developer.