草庐IT

php 5.3 转换 array_walk_recursive

coder 2024-04-19 原文

我有以下代码,我想摆脱调用时间传递引用,(从 5.2 转换为 5.3)但我不确定正确的方法是什么这将是(类,全局变量,?)

这是一个应该包含所有内容的键盘 http://codepad.org/ombgFPMR

<?php

function count_things($item, $key, $total) {
    $total++;
}

$counts = array(100 => 1,
            101 => 1,
            102 => array(
                106 => 1,
                107 => 1
            ),
            103 => 1,
            104 => 1,
            105 => array(
                108 => 1,
                109 => array(
                    110 => 1,
                    111 => 1,
                    112 => 1
                )
            )
        );

foreach($counts as $key => $count) {
    $total = 0;

    if(is_array($count)) {
            $total++;
            /* The below is a logic error. Array elements that contain arrays do not get
               the callback function called on them. Therefore, any children with children
               of their own will not be counted. In the output of this paste,
               the final key, $final_counts[105]['total'], should have a value of 6, but it
               actually has a value of 5. */
    array_walk_recursive($count, 'count_things', &$total);
} else {
            $total = $count;
    }

    $final_counts[$key]['total'] = $total;
}   

print_r($final_counts);

?>

输出如下:

Array
(
[100] => Array
    (
        [total] => 1
    )

[101] => Array
    (
        [total] => 1
    )

[102] => Array
    (
        [total] => 3
    )

[103] => Array
    (
        [total] => 1
    )

[104] => Array
    (
        [total] => 1
    )

[105] => Array
    (
        [total] => 5
    )

)

最佳答案

您可以将 countCOUNT_RECURSIVE 标志一起使用。

你应该为此使用闭包,它们是在 5.3.0 中引入的,所以它们应该可以工作。

<?php

$counts = array(
    100 => 1,
    101 => 1,
    102 => array(
        106 => 1,
        107 => 1
    ),
    103 => 1,
    104 => 1,
    105 => array(
        108 => 1,
        109 => array(
            110 => 1,
            111 => 1,
            112 => 1
        )
    )
);

$final_counts = array();

foreach($counts as $key => $count) {

    if(is_array($count)) {
        $total = 1;
        array_walk_recursive($count, function() use (&$total) {
            $total++;
        });
    } else {
        $total = $count;
    }

    $final_counts[$key]['total'] = $total;
}

print_r($final_counts);

如果您将问题放在上下文中,我可能会提供更好的解决方案。

关于php 5.3 转换 array_walk_recursive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922563/

有关php 5.3 转换 array_walk_recursive的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  3. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  6. Ruby Koans about_array_assignment - 非平行与平行分配歧视 - 2

    通过ruby​​koans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John

  7. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  8. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

  9. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  10. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

随机推荐