array_walk_recursive-修改键和值 [英] array_walk_recursive - modify both keys and values

查看:116
本文介绍了array_walk_recursive-修改键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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);
}

推荐答案

array_walk_recursive仅将用户函数应用于数组的VALUES,而不应用于索引(我认为这与事实有关,即索引数组的唯一性必须是唯一的,因此您无法操作它们).最好的办法是为自己编写一个递归函数.以下应该可以工作:

array_walk_recursive does ONLY apply the user function on the VALUES of an array, not on indexes (I think it has something to with the fact, that the indexes of an array have to be unique, so you cannot manipulate them). Best thing would be to write a recursive function on yourself. The following should work:

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);

这篇关于array_walk_recursive-修改键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆