【问题标题】:how to make array_walk_recursive ignore for specific key values如何使 array_walk_recursive 忽略特定键值
【发布时间】:2014-03-07 19:17:04
【问题描述】:

我想创建一个array_walk_recursive($my_array, 'myfunction');,但前提是密钥不包含字符串_ignore

为了更清楚:

function Capitalize(&$input)
{
    $input = strtoupper($input);    
}

$my_array = array();    
$my_array[0]['title']="apply to this";
$my_array[0]['info']="apply to this also";
$my_array[0]['data_ignore']="don't touch this!!!!";
$my_array[1]['title']="you can change this";
$my_array[1]['info']="you can also change this";
$my_array[1]['data_ignore']="i said don't touch this! cant you see the key's name?";

array_walk_recursive($my_array, 'Capitalize');

// i wish the function to be applied to all elements except the ['data_ignore'] ones

附言当然我的问题不是关于大小写,我只是提供一个适当的例子。

p.s.2 我尝试了什么:我找不到任何方法将密钥传递给函数,所以我可以在那里编程绕过:(

p.s.3 如果您能回答“如何从引用的变量中获取键名?”的问题,我的问题将得到解决

【问题讨论】:

    标签: php arrays recursion


    【解决方案1】:

    试试

    function Capitalize(&$input,$key){
        if(strpos($key,"_ignore") ===FALSE ){
          $input = strtoupper($input);    
        }
    }
    

    查看演示here

    【讨论】:

    • 哦,$key 是如何传递的?! (谢谢!-当我能够接受答案时-需要等待)
    • 不用传,第二个参数是key 查看更多信息in2.php.net/manual/en/function.array-walk-recursive.php
    • 需要找一堵墙来敲我的头。难的。再次感谢 Nouphal 先生 :) Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.
    • @Sharky:这也发生在我身上。我之前必须做类似的事情,我写了一个递归函数来完成。仅仅几个月后,我才意识到可以使用第二个参数访问密钥。阅读该函数的文档总是一个好主意!干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多