0
votes

enter image description here

How to display the category structure like WordPress using php?

Array

( [0] => stdClass Object ( [cat_id] => 64 [name] => Bathing Soap [slug] => bathing-soap [cat_taxonomy_id] => 65 [taxonomy] => product_cat [parent] => 63 )

[1] => stdClass Object
    (
        [cat_id] => 65
        [name] => Chemical
        [slug] => chemical
        [cat_taxonomy_id] => 66
        [taxonomy] => product_cat
        [parent] => 64
    )

[2] => stdClass Object
    (
        [cat_id] => 63
        [name] => Soap
        [slug] => soap
        [cat_taxonomy_id] => 64
        [taxonomy] => product_cat
        [parent] => 0
    )

)

2
I have tried with get the parent id of the each element only after that i duknow how to structure that and display like tree :(Aaru

2 Answers

1
votes

In your example is arrays as you store this records in database.

For output tree structure you should convert it to tree structure.

For example:

  1. Change array and use cat_id as key in main array.
  2. Add to each item field childs = array(); And store in this array ids for childs category.
  3. Find root categories (where parent == 0) and save ids in childs field for item with key "0".

Step 1 you can make when you load data from fro database. Steps 2 and 3 can make in one iteration (foreach)

After this your example will similar

array(
  [0] => stdClass Object
    (
      [cat_id] => 0,
      [childs] => array( [0]=>63 )
      ...
    )
  [63]=> stdClass Object
    (
      [cat_id] => 63,
      [childs] => array( [0]=>64 )
      ...
    ) 

Then you can output tree. Just begin with key = 0 and output all childs. For each child in first out title and then all childs. You should use recursion function.

1
votes

I have tried this below link. you can also try this below Link

http://stevenbuick.com/category-hierarchy-with-codeigniter-and-jstree/