如何递归地对特定数组键的所有值求和?

发布于 2024-09-24 07:16:47 字数 404 浏览 5 评论 0原文

我有一个像这样的数组:

Array
(
    [1000] => Array
        (
            [pv] => 36
        )

    [1101] => Array
        (
            [1102] => Array
                (
                    [pv] => 92
                )

            [pv] => 38
        )

    [pv] => 64
)

如何找到带有键“pv”的所有数组元素的总和,无论它们出现的深度如何?

对于此示例,结果将为 36+92+38+64 = 230

I have an array like this:

Array
(
    [1000] => Array
        (
            [pv] => 36
        )

    [1101] => Array
        (
            [1102] => Array
                (
                    [pv] => 92
                )

            [pv] => 38
        )

    [pv] => 64
)

How I can find the sum of all array elements with key 'pv', regardless of the depth at which they appear?

For this example the result will be 36+92+38+64 = 230

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

孤云独去闲 2024-10-01 07:16:47

另一种选择:

$sum = 0;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
    if($key == 'pv')
        $sum += $value;
}
echo $sum;

更新: 只是想我会提到此方法使用 PHP SPL 迭代器。


Salathe 编辑:

过滤键并对值求和(无需编写自定义迭代器)的一种简单(相对)方法是使用RegexIterator,将生成的迭代器转换为数组,并对其使用方便的 array_sum 函数。这纯粹是一项学术练习,我当然不会提倡将其作为实现这一目标的最佳方式......但是,它只是一行代码。 :)

$sum = array_sum(
    iterator_to_array(
        new RegexIterator(
            new RecursiveIteratorIterator(
                new RecursiveArrayIterator($array)
            ),
            '/^pv$/D',
            RegexIterator::MATCH,
            RegexIterator::USE_KEY
        ),
        false
    )
);

Another alternative:

$sum = 0;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
    if($key == 'pv')
        $sum += $value;
}
echo $sum;

Update: Just thought I'd mention that this method uses the PHP SPL Iterators.


Salathe Edit:

A simple (relatively) way to filter the keys and to sum the values (without writing a custom Iterator) would be to do some filtering with a RegexIterator, convert the resulting iterator into an array and use the handy array_sum function on it. This is purely an academic exercise and I certainly wouldn't advocate it as the best way to achieve this... however, it is just one line-of-code. :)

$sum = array_sum(
    iterator_to_array(
        new RegexIterator(
            new RecursiveIteratorIterator(
                new RecursiveArrayIterator($array)
            ),
            '/^pv$/D',
            RegexIterator::MATCH,
            RegexIterator::USE_KEY
        ),
        false
    )
);
海夕 2024-10-01 07:16:47
function addPV($array){
  $sum = 0;
  foreach($array as $key => $a){
    if (is_array($a)){
       $sum += addPV($a);
    }else if($key == 'pv') {
       $sum += $a;
    }
  }
  return $sum;
}
function addPV($array){
  $sum = 0;
  foreach($array as $key => $a){
    if (is_array($a)){
       $sum += addPV($a);
    }else if($key == 'pv') {
       $sum += $a;
    }
  }
  return $sum;
}
久随 2024-10-01 07:16:47

基于@Ali Sattari答案

function sum($v, $w) {
    return $v + (is_array($w) ? 
        array_reduce($w, __FUNCTION__) : $w);
}

based on @Ali Sattari answer

function sum($v, $w) {
    return $v + (is_array($w) ? 
        array_reduce($w, __FUNCTION__) : $w);
}
枫以 2024-10-01 07:16:47

您可以使用 array_reduce 或 array_walk_recursive 函数以及您自己的自定义回调函数:

function sum($v, $w)
{
    $v += $w;
    return $v;
}

$total = array_reduce($your_array, "sum");

you can use array_reduce or array_walk_recursive functions and a custom call back function of yourself:

function sum($v, $w)
{
    $v += $w;
    return $v;
}

$total = array_reduce($your_array, "sum");
流年已逝 2024-10-01 07:16:47
function SumRecursiveByKey($array,$key)
{
    $total = 0;
    foreach($array as $_key => $value)
    {
        if(is_array($value))
        {
            $total += SumRecursiveByKey($array,$key);
        }elseif($_key == $key)
        {
             $total += $value;
        }
    }
    return $total;
}

使用 like

$summed_items = SumRecursiveByKey($myArray,'pv');

这会给你更多的余地来检查替代键的膨胀。

function SumRecursiveByKey($array,$key)
{
    $total = 0;
    foreach($array as $_key => $value)
    {
        if(is_array($value))
        {
            $total += SumRecursiveByKey($array,$key);
        }elseif($_key == $key)
        {
             $total += $value;
        }
    }
    return $total;
}

use like

$summed_items = SumRecursiveByKey($myArray,'pv');

This would give you more leeway in checking alternative keys a swell.

北城挽邺 2024-10-01 07:16:47
$sum = 0;

function sumArray($item, $key, &$sum)
{
    if ($key == 'pv')
       $sum += $item;
}

array_walk_recursive($array, 'sumArray',&$sum);
echo $sum;
$sum = 0;

function sumArray($item, $key, &$sum)
{
    if ($key == 'pv')
       $sum += $item;
}

array_walk_recursive($array, 'sumArray',&$sum);
echo $sum;
漫漫岁月 2024-10-01 07:16:47
$array = array('1000'=> array('pv'=>36), array('1101' => array('pv'=>92)));

$total = 0;
foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array)) as $sub)
{
 $total += (int)  $sub;
}
print_r($total);
$array = array('1000'=> array('pv'=>36), array('1101' => array('pv'=>92)));

$total = 0;
foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array)) as $sub)
{
 $total += (int)  $sub;
}
print_r($total);
梦里南柯 2024-10-01 07:16:47
private function calculateUserGv($userId) {
    $group = $this->arrayUnder($this->_user_tree, $userId);
    global $gv;
    $gv = 0;
    $gv    = $this->gvRecursive($group);
    return;
}

private function gvRecursive($group) {
    global $gv;
    foreach ($group as $key => $val) {
        if ($key == 'pv') {
            $gv += $group[$key];
        }
        else {
            $this->gvRecursive($val);
        }
    }
    return $gv;
}
private function calculateUserGv($userId) {
    $group = $this->arrayUnder($this->_user_tree, $userId);
    global $gv;
    $gv = 0;
    $gv    = $this->gvRecursive($group);
    return;
}

private function gvRecursive($group) {
    global $gv;
    foreach ($group as $key => $val) {
        if ($key == 'pv') {
            $gv += $group[$key];
        }
        else {
            $this->gvRecursive($val);
        }
    }
    return $gv;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文