如何从多维PHP数组中检索子集?

时间:2018-04-24 08:19:42

标签: php

这是一个PHP数组:

<section>headline:
  <p class="fragment">text</p>
  <p class="fragment">text</p>
  <p class="fragment blink">text that should blink in pink </p>
</section>

target_a,target_b,...,target_n永远不会相互重复。

我需要一个函数:superFind(),它可以:

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

即,对于给定的superFind('target_e'); // supposed to return: 'target_e' => [ 'target_f' => [] ], superFind('target_a'); // supposed to return: [] 值,返回子集(更好地包括其自身)

我试过递归函数和https://packagist.org/packages/nicmart/tree,无法弄清楚如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

这应该适合你:

$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";
}

输出:

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

)

target_a: Array
(
)

target_q: Not found