简体   繁体   中英

Replace empty values in an array with defaults

I have two arrays, the first is the result I get from a function and the second contains default values. I want to replace empty values from first array with values from second array.

$result = [
    'NOTNULL',
    null,
    null,
    null,
    null
];

$defaults = [
    'default1',
    'default2',
    [
        null,
        null,
        null
    ]
];

# transforming $result array (to have the same form as $defaults array)
array_splice($result, 2, 3, [array_slice($result, 2)]);

$result = array_replace_recursive(
    $default,
    $result
);

Output:

Array (
    [0] => NOTNULL
    [1] => null
    [2] => Array (
        [0] => Array ()
        [1] => null
        [2] => null
     )
)

Expected:

Array (
    [0] => NOTNULL
    [1] => default2
    [2] => Array (
        [0] => null
        [1] => null
        [2] => null
    )
);

I know I get that result because array_replace_recursive replaces elements from passed arrays into the first array recursively, but how can I change only values that aren't empty?

Maybe should I do something like this?

$result[0] = (array_key_exists(0, $result) || $result[0] === null) ? $defaults[0] : $result[0];

... for every key in the array? I want preserve empty values that are empty in two arrays. At this moment this is the only solution I've found, but it's not very elegant...

How can I get the expected result? I don't have any ideas.

<?php
$result = array(
    'NOTNULL',
    null,
    null,
    array(null, null),
    null
);

$defaults = array(
    'default1',
    'default2',
    array(
        null,
        null,
        null
    ),
    array('tea', 'biscuit')
);


function myRecursiveArrayMerge($result, $defaults){
        foreach ($result as $index => $value) {
                if(is_array($value))
                        $result[$index] = myRecursiveArrayMerge($value, $defaults[$index]);

                if ($value === null && isset($defaults[$index]))
                        $result[$index] = $defaults[$index];
        }

        return $result;

}
$finalResult = myRecursiveArrayMerge($result, $defaults);

print_r($finalResult);
<?php

$result = array(
    'NOTNULL',
    null,
    null,
    null,
    null
);

$defaults = array(
    'default1',
    'default2',
    array(
        null,
        null,
        null
    )
);

echo "Before\n";
var_dump($result);

foreach ($result as $index => $value) {
    if ($value === null && isset($defaults[$index]))
        $result[$index] = $defaults[$index];
}   

echo "After\n";
var_dump($result);

http://ideone.com/4HMGH4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM