Mohammad Masoudian
Mohammad Masoudian

Reputation: 3491

make tree with a multidimensional array

how to make tree with the following multidimensional array?

the child items have a non-zero parentID

Array
(
    [0] => Array
        (
            [id] => 6
            [title] => zzz
            [parentID] => 0
            [parentName] => 
            [section] => articles
            [sort] => 0
            [level] => 0
        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 7
                    [title] => 7
                    [parentID] => 6
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [id] => 8
                            [title] => 8
                            [parentID] => 7
                            [parentName] => 
                            [section] => articles
                            [sort] => 0
                            [level] => 0
                        )

                )

        )

    [2] => Array
        (
            [id] => 1
            [title] => تست
            [parentID] => 0
            [parentName] => 
            [section] => articles
            [sort] => 0
            [level] => 0
        )

    [3] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [title] => 4
                    [parentID] => 1
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

            [1] => Array
                (
                    [id] => 5
                    [title] => 5
                    [parentID] => 1
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

        )

)

if i want to show items by id, i need following result :

6
-7
--8
1
-4
-5

my attempt :

foreach ($array as $category)
{
    $dash = str_repeat("-", array_depth($category));
    echo $dash . $category['id'];
}

Upvotes: 1

Views: 826

Answers (1)

Cheong BC
Cheong BC

Reputation: 316

Is that what you want it?

function arrayStack( $array, $dash ){

   foreach($array as $value){
        if(isset($value['id'])){
            echo str_repeat("-", $dash).$value['id'].',';
        }else{
            $dash++;
            arrayStack( $value, $dash );
            $dash--;
        }
   }

} 

arrayStack( $myArray, 0 );

Demo

Upvotes: 3

Related Questions