Home > Blockchain >  How to get items with superior and inferior relationship from a flat array
How to get items with superior and inferior relationship from a flat array

Time:03-21

I have an array like this

[
    [
        'id'=>1,
        'parent'=>0
    ],
    [
        'id'=>2,
        'parent'=>1
    ],
    [
        'id'=>3,
        'parent'=>0
    ],
    [
        'id'=>4,
        'parent'=>2
    ],
    [
        'id'=>5,
        'parent'=>0
    ],
    [
        'id'=>6,
        'parent'=>0
    ]
]

For example my function is like this:

public static function getAllChildren($categories, $parent_id)

I want data like this,Get data by an id:

[
    [
        'id'=>1,
        'parent'=>0
    ],
    [
        'id'=>2,
        'parent'=>1
    ],
    [
        'id'=>4,
        'parent'=>2
    ]
]

I've tried static method recursion and static variables, but, when calling this method from multiple places, the data stacks up(google translate)

CodePudding user response:

Here is the solution

$temp = array_unique(array_column($arr, 'parent'));
$unique_arr = array_intersect_key($arr, $temp);

CodePudding user response:

Try this. However I am sure there is a way to solve this problem more efficiently and reduce time complexity.

<?php

function getAllChildren($categories, $parent_id, $arr = []) {
    for ($i=0; $i < count($categories); $i  ) {
        if($categories[$i]['parent'] == $parent_id) {
            array_push($arr, $categories[$i]);
            return getAllChildren($categories, $categories[$i]['id'], $arr);
        }
    }
    
    return $arr;
};

$data = [
    [
        'id'=>1,
        'parent'=>0
    ],
    [
        'id'=>2,
        'parent'=>1
    ],
    [
        'id'=>3,
        'parent'=>0
    ],
    [
        'id'=>4,
        'parent'=>2
    ],
    [
        'id'=>5,
        'parent'=>0
    ],
    [
        'id'=>6,
        'parent'=>0
    ]
];

$result = getAllChildren($data, 0);
  • Related