gpt4 book ai didi

php 5.3 转换 array_walk_recursive

转载 作者:可可西里 更新时间:2023-10-31 23:33:23 24 4
gpt4 key购买 nike

我有以下代码,我想摆脱调用时间传递引用,(从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com