0

Here is a PHP array:

$arr = [
    'target_a' => [],
    'target_b' => [],
    'target_c' => [
        'target_d' => [],
        'target_e' => [
            'target_f' => []
        ],
    ],
    'target_g' => [],
];

target_a ,target_b, ... , target_n is never duplicated with each other.

I need a function: superFind() , which can do:

superFind('target_e');
// supposed to return:
'target_e' => [
    'target_f' => []
],

superFind('target_a');
// supposed to return:
[]

ie, for a given target_x value,return a subset(better including itself)

I've tried recursively function and https://packagist.org/packages/nicmart/tree , cannot figure out how to solve this.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Phoenix
  • 1,055
  • 1
  • 12
  • 27

1 Answers1

1

This should do the job for you:

$arr = [
    'target_a' => [],
    'target_b' => [],
    'target_c' => [
        'target_d' => [],
        'target_e' => [
            'target_f' => []
        ],
    ],
    'target_g' => [],
];

function superFind($arr, $target) {
    foreach ($arr as $key => $value) {
        if ($key == $target) return $value;
        if (is_array($value)) {
            if (($found = superFind($value, $target)) !== false) return $found;
        }
    }
    return false;
}

foreach (['target_e', 'target_a', 'target_q'] as $test) {
    echo "$test: ";
    if (($found = superFind($arr, $test)) !== false) print_r($found);
    else echo "Not found";
    echo "\n";
}

Output:

target_e: Array
(
    [target_f] => Array
        (
        )

)

target_a: Array
(
)

target_q: Not found
Nick
  • 138,499
  • 22
  • 57
  • 95