Search code examples
phpmultidimensional-arrayarray-unset

Remove elements within nested array


I have a PHP array as follows:

$errors = array('Price'=>array('not a positive decimal number'=> 1), 'TaxYear'=>array('not a positive integer'=>1, 'not 4 digits'=>1), 'Address'=>array(''=>1), 'State'=>array('not 2 letters'=>1, ''=>1), 'ListDate'=>array(''=>1, 'some test'=>1, ''=>1));

echo '$errors:<pre>' . print_r($errors,1) . '</pre>';

Array
(
[Price] => Array
    (
        [not a positive decimal number] => 1
    )

[TaxYear] => Array
    (
        [not a positive integer] => 1
        [not 4 digits] => 1
    )

[Address] => Array
    (
        [] => 1
    )

[State] => Array
    (
        [not 2 letters] => 1
        [] => 1
    )

[ListDate] => Array
    (
        [] => 1
        [some test] => 1
    )

)

The goal is to create another array from this one that looks like this:

Array
(
[Price] => Array
    (
        [not a positive decimal number] => 1
    )

[TaxYear] => Array
    (
        [not a positive integer] => 1
        [not 4 digits] => 1
    )

[State] => Array
    (
        [not 2 letters] => 1
    )

[ListDate] => Array
    (
        [some test] => 1
    )

)

Essentially any element in a nested array that has [] as its element name needs to be removed. If any keys in the outer array have only 1 error and that error has an element name of [], then the key in the outer array needs to be removed as well (see [Address] in the example for an illustration of this). What is the best way to achieve this?


Solution

  • You could use something like this to selectively copy elements:

    $filtered = array();
    foreach($errors as $category => $pairs) {
        foreach($pairs as $key => $value) {
            if($key != '') {
                $filtered[$category][$key] = $value;
            }
        }
    }