array_walk_recursive - 修改键和值

时间:2011-09-20 18:42:19

标签: php

如何使用array_walk_recursive ??

修改键和值

此处仅编码值

function _utf8_encode($arr){
    array_walk_recursive($arr, 'utf8_enc');

    return $arr;
}

function utf8_enc(&$value, &$key){
    $value = utf8_encode($value);
    $key = utf8_encode($key);
}

3 个答案:

答案 0 :(得分:7)

array_walk_recursive仅在数组的VALUES上应用用户函数,而不是在索引上应用(我认为它与事实有关,即数组的索引必须是唯一的,因此您无法操作他们)。最好的办法就是自己写一个递归函数。以下应该有效:

function utf8enc($array) {
    if (!is_array($array)) return;
    $helper = array();
    foreach ($array as $key => $value) $helper[utf8_encode($key)] = is_array($value) ? utf8enc($value) : utf8_encode($value);
    return $helper;
}

$enc_array = utf8enc($your_array);

答案 1 :(得分:1)

这是我的递归函数,它不仅可以将数组的值更改为array_walk_recursive(),而且可以更改给定数组的键。它还保留了数组的顺序。

/**
 * Change values and keys in the given array recursively keeping the array order.
 *
 * @param array    $_array    The original array.
 * @param callable $_callback The callback function takes 2 parameters (key, value)
 *                            and returns an array [newKey, newValue] or null if nothing has been changed.
 *
 * @return void
 */
function modifyArrayRecursive(array &$_array, callable $_callback): void
{
    $keys = \array_keys($_array);
    foreach ($keys as $keyIndex => $key) {
        $value = &$_array[$key];
        if (\is_array($value)) {
            modifyArrayRecursive($value, $_callback);
            continue;
        }

        $newKey = $key;
        $newValue = $value;
        $newPair = $_callback ($key, $value);
        if ($newPair !== null) {
            [$newKey, $newValue] = $newPair;
        }

        $keys[$keyIndex] = $newKey;
        $_array[$key] = $newValue;
    }

    $_array = \array_combine($keys, $_array);
}

/**
 * Usage example
 */
modifyArrayRecursive($keyboardArr, function ($key, $value) {
    if ($value === 'some value') {
        return ['new_key_for_this_value', $value];
    }

    return null;
});

答案 2 :(得分:0)

除了rabudde的答案之外,还有另一个递归函数:

  function utf8_encode_array($array_to_encode=array()){

        $encoded_array=array();

        if(is_array($array_to_encode)){

            foreach($array_to_encode as $key => $value){

                $key=utf8_encode($key);

                if(is_array($value)){

                    $encoded_array[$key]=utf8_encode_array($value);

                }
                else{

                    $encoded_array[$key]=utf8_encode($value);

                }
            }
        }

        return $encoded_array;
    }