加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php 5.3转换array_walk_recursive

发布时间:2020-12-13 16:16:42 所属栏目:PHP教程 来源:网络整理
导读:我有以下代码,我想摆脱调用时间传递引用,(从5.2转换为5.3)但我不确定究竟是什么方法可以做到这一点(类,全局变量,?) 这是一个应该包含所有内容的键盘 http://codepad.org/ombgFPMR ?phpfunction count_things($item,$key,$total) { $total++;}$counts = arra
我有以下代码,我想摆脱调用时间传递引用,(从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
    )

)

解决方法

您可以使用带有COUNT_RECURSIVE标志的count.

您应该使用闭包,这些是在5.3.0中引入的,因此它们应该可以工作.

<?php

$counts = array(
    100 => 1,102 => array(
        106 => 1,107 => 1
    ),105 => array(
        108 => 1,109 => array(
            110 => 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);

如果你把问题放在上下文中,我或许可以提供更好的解决方案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读