English 中文(简体)
纵观多面阵列的深层价值与行文结构不一致
原标题:Sum deep column values of a multidimensional array with inconsistent row structures

我拥有一个最大深度为4级的多面阵列,但并非所有栏目都存在于低级,有些栏目含有分门槛而不是原始价值。

我需要计算一栏数值的总和。

我希望得到总额[价格]、[结果]和[儿童]的资金,但未能扭转这一水平。

我应当举这个例子:price=380成年人=5 和儿童=1

我的投入阵列如下:

[
    8 => [
        2 => [
             num_rooms  => 2,
             adults  => [1, 1],
             children  => [0, 0],
             prices  => [50, 50],
             price  => 130,
             supp  => 30,
        ],
        3 => [
             num_rooms  => 1,
             adults  => [1],
             prices  => [100],
             price  => 150,
             supp  => 50,
        ],
    ],
    1 => [
        2 => [
             num_rooms  => 2,
             adults  => [1, 1],
             children  => [1, 0],
             prices  => [75, 75],
             price  => 170,
             supp  => 20,
        ],
    ],
]
最佳回答

这一工作应当:

$price = 0;
$adults = 0;
$children = 0;

foreach($arr as $l1_key => $l1_value)           // iterates over the first level array
{
    foreach($l1_value as $l2_key => $l2_value)  // iterates over second level arrays
    {
         $price += $l2_value[ price ];          // add up price totals

         foreach($l2_value[ adults ] as $value) // iterate through adults array values
         {
             $adults += $value;                 // sum up adult count
         }

         foreach($l2_value[ children ] as $value) // iterate through children array values
         {
             $children += $value;                // sum up children count
         }
    }
}

// now $price, $adults, and $children contain the totals for each
问题回答

两处 lo和助手阵列:

$sums = array (  price  => 0,  adults  => 0,  children  => 0 );

foreach($array as $outer) {
  foreach($outer as $inner) {
    $sums[ price ] += $inner[ price ];
    $sums[ adults ] += array_sum($inner[ adults ]);
    $sums[ children ] += array_sum($inner[ children ]);
  }
}

print_r($sums);

• 采用更动态的内 lo:

foreach($array as $outer) {
  foreach($outer as $inner) {
    foreach($sums as $key => &$v)
      $v += is_array($inner[$key])
        ? array_sum($inner[$key])
        : $inner[$key];
  }
}

我对这部法典进行了测试,但与此同时,我不知道你是如何去的。 I m see 350?

$sums = getSum($arr);

print_r($sums);

function getSum($arr) {

    $sums = array();
    $sums2 = array();
    $sums[ adults ] = 0;
    $sums2[ adults ] = 0;
    $sums[ children ] = 0;
    $sums2[ children ] = 0;
    $sums[ prices ] = 0;
    $sums2[ prices ] = 0;

    foreach ($arr as $key => $value) {

        $do_not_recurse = false;
        switch ($key) {
            case  adults :
                $do_not_recurse = true;
                foreach ($value as $adults)
                    $sums[ adults ] += $adults;
                break;
            case  children :
                $do_not_recurse = true;
                foreach ($value as $children)
                    $sums[ children ] += $children;
                break;
            case  prices :
                $do_not_recurse = true;
                foreach ($value as $price)
                    $sums[ prices ] += $price;
                break;
            default:
                break;
        }

        if (is_array($value))
            $sums2 = getSum($value);
    }

    $sums[ adults ] += $sums2[ adults ];
    $sums[ children ] += $sums2[ children ];
    $sums[ prices ] += $sums2[ prices ];

    return $sums;
}

• 处理任何深度或阵列结构,仅用你正在寻找的名称摘录:

function find($term, $array) {
  $count = 0;
  foreach ($array as $item)
    if (is_array($item)) $count += find($term, $item);
  if (isset($array[$term]) {
    if (is_array($array[$term])) $count += array_sum($array[$term]);
    else $count += $array[$term];
  }
  return $count;
}

echo count( price , <the array>);
echo count( adults , <the array>);
echo count( children , <the array>);

您的多层面阵列的第一层可被安全地忽略,视之为无关紧要,因此,array_joint(......$array)可用于在结构上统一,而不必写上foreach(<>,并宣布一个额外的变量。

为使下级升温并动态地完成每一栏的合计工作,你可以将每一数值作为阵列(一致性),然后在该栏的以往储存价值上加上这一数值。

解释无条件投放:

  • When casting a scalar or null value to an array, the value becomes the lone element of the array.
  • When casting an array to be an array, there is no change (because it is already an array).

法典:《Demo

$result = [];
foreach (array_merge(...$array) as $row) {
    foreach ($row as $k => $v) {
        $result[$k] = ($result[$k] ?? 0) + array_sum((array) $v);
    }
}
var_export($result);

产出:

array (
   num_rooms  => 5,
   adults  => 5,
   children  => 1,
   prices  => 350,
   price  => 450,
   supp  => 100,
)




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签