How can PHP developers efficiently filter and store specific data from nested objects and arrays?

When dealing with nested objects and arrays in PHP, developers can efficiently filter and store specific data by using recursive functions to traverse through the nested structures and extract the desired information. By recursively iterating through the nested elements, developers can target and extract the specific data they need, storing it in variables or arrays for further processing.

function filterNestedData($data, $key) {
    $result = [];

    foreach ($data as $item) {
        if (is_array($item) || is_object($item)) {
            $result = array_merge($result, filterNestedData((array)$item, $key));
        } else {
            if ($key === $item) {
                $result[] = $item;
            }
        }
    }

    return $result;
}

// Example usage
$data = [
    'key1' => 'value1',
    'key2' => [
        'key3' => 'value2',
        'key4' => 'value3'
    ],
    'key5' => 'value4'
];

$filteredData = filterNestedData($data, 'value3');
print_r($filteredData);