将 3d 数组转换为唯一值的关联数组并对它们的相关值求和

发布于 2024-11-14 18:39:46 字数 1037 浏览 4 评论 0原文

我需要展平多维数组以形成唯一值及其总和的关联数组。

我的示例数组:

[
    [
        'winners' => [
            'Gold Member',
            'CROTCH SNIFFER',
            'TEAM #1'
        ],     
        'prizeTotal' => 20
    ],
    [
        'winners' => [
            'TEAM #1',
            'CROTCH SNIFFER'
        ],     
        'prizeTotal' => 60
    ],
    [
        'winners' => [
            'Gold Member',
            'TEAM #1'
        ],     
        'prizeTotal' => 30
    ],
    [
        'winners' => [
            'TEAM #1',
            'TEAM #2',
            'SCREW-NUT-BOLT'
        ],     
        'prizeTotal' => 90
    ]
]

请原谅这些名字...这不是我的数据库。

在每个数据集中,prizeTotal 被授予获胜者中的每个值代码>子数组。

如何对 winners 值进行分组并对它们各自的 prizeTotal 值进行求和?

期望的结果:

array (
  'Gold Member' => 50,
  'CROTCH SNIFFER' => 80,
  'TEAM #1' => 200,
  'TEAM #2' => 90,
  'SCREW-NUT-BOLT' => 90,
)

I need to flatten a multidimensional array to form an associative array of unique values and their sums.

My sample array:

[
    [
        'winners' => [
            'Gold Member',
            'CROTCH SNIFFER',
            'TEAM #1'
        ],     
        'prizeTotal' => 20
    ],
    [
        'winners' => [
            'TEAM #1',
            'CROTCH SNIFFER'
        ],     
        'prizeTotal' => 60
    ],
    [
        'winners' => [
            'Gold Member',
            'TEAM #1'
        ],     
        'prizeTotal' => 30
    ],
    [
        'winners' => [
            'TEAM #1',
            'TEAM #2',
            'SCREW-NUT-BOLT'
        ],     
        'prizeTotal' => 90
    ]
]

Please forgive the names...it's not my DB.

In each data set, the prizeTotal is awarded to each value in the winners subarray.

How can I group the winners values and sum their respective prizeTotal values?

Desired result:

array (
  'Gold Member' => 50,
  'CROTCH SNIFFER' => 80,
  'TEAM #1' => 200,
  'TEAM #2' => 90,
  'SCREW-NUT-BOLT' => 90,
)

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

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

发布评论

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

评论(4

半衬遮猫 2024-11-21 18:39:47

您需要创建一个新数组来保存您的结果,然后对于每个现有数组,检查您是否已经为该团队处理了一个数组。

如果有,则只需将prizeTotal添加到存储在新数组条目中的prizeTotal即可那个团队。

如果没有,只需将团队的条目添加到新数组中即可。

You need to make a new array to hold your results, then for each of your existing arrays, check if you're already processed one for that team

If you have, then simply add the prizeTotal to the prizeTotal stored in your new array's entry for that team.

If not, simply add the team's entry to your new array.

束缚m 2024-11-21 18:39:47

要生成唯一团队及其累积得分的关联数组:

  1. 使用循环访问每个数据子集
  2. 使用 extract() 方便地访问作为单独变量的获胜者和prizeTotal 数据。
  3. 循环获胜者元素
  4. 将获胜者声明为结果数组中的键,其值应为prizeTotal加上缓存值(如果没有缓存值则为零)。

代码:(演示

$result = [];
foreach ($array as $set) {
    extract($set);
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);

“数组解构”可以代替调用 extract()也创建单独的变量。

$result = [];
foreach ($array as ['winners' => $winners, 'prizeTotal' => $prizeTotal]) {
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);

To generate an associative array of unique teams and their cumulative scores:

  1. Use a loop to access each data subset
  2. Use extract() to conveniently access the winner and prizeTotal data as individual variables.
  3. Loop the winner elements
  4. Declare the winner as the key in the result array and the value should be the prizeTotal plus the cached value (or zero if there is no cached value).

Code: (Demo)

$result = [];
foreach ($array as $set) {
    extract($set);
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);

Instead of calling extract(), "array destructuring" can create individual variables as well.

$result = [];
foreach ($array as ['winners' => $winners, 'prizeTotal' => $prizeTotal]) {
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);
魂归处 2024-11-21 18:39:47

我制作了一个模仿 mysql SUM()GROUP BY 的函数。我希望它能满足您的需求:

           $in_a = array(
                array("a" => 0,"b"=>0,"s"=> 1),
                array("a" => 0,"b"=>0,"s"=> 2),
                array("a" => 1,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 1,"b"=>0,"s"=> 1),         
                array("a" => 0,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>0,"s"=> 1),         
            );//input array exaple
            $group_by_a = array("a","b");//input array will be grouped by these
            $sum_a = array("s"); //'s' values of input will be summed
            $out_a = array(); //this is the output array

            foreach($in_a as $in_i => $in)
            {
                $add = false;
                foreach($out_a as $out_i => $out)
                {
                    $add = true;
                    foreach($group_by_a as $group_by)
                        if($in[$group_by] != $out[$group_by])
                        {
                            $add = false; 
                            break;
                        }                   
                    if($add)
                    {
                        foreach($sum_a as $sum)
                            $out_a[$out_i][$sum] += $in[$sum];  
                        break;
                    }
                }
                if(!$add)
                {
                    foreach($group_by_a as $group_by)
                        $out_a[$in_i][$group_by] = $in[$group_by];
                    foreach($sum_a as $sum)
                        $out_a[$in_i][$sum] = $in[$sum];                    
                }                   
            }

结果:

Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 0
            [s] => 3
        )

    [2] => Array
        (
            [a] => 1
            [b] => 1
            [s] => 2
        )

    [3] => Array
        (
            [a] => 0
            [b] => 1
            [s] => 3
        )

    [5] => Array
        (
            [a] => 1
            [b] => 0
            [s] => 2
        )

)

I have made a function that imitates mysql SUM() and GROUP BY. I hope it will fit your needs:

           $in_a = array(
                array("a" => 0,"b"=>0,"s"=> 1),
                array("a" => 0,"b"=>0,"s"=> 2),
                array("a" => 1,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 1,"b"=>0,"s"=> 1),         
                array("a" => 0,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>0,"s"=> 1),         
            );//input array exaple
            $group_by_a = array("a","b");//input array will be grouped by these
            $sum_a = array("s"); //'s' values of input will be summed
            $out_a = array(); //this is the output array

            foreach($in_a as $in_i => $in)
            {
                $add = false;
                foreach($out_a as $out_i => $out)
                {
                    $add = true;
                    foreach($group_by_a as $group_by)
                        if($in[$group_by] != $out[$group_by])
                        {
                            $add = false; 
                            break;
                        }                   
                    if($add)
                    {
                        foreach($sum_a as $sum)
                            $out_a[$out_i][$sum] += $in[$sum];  
                        break;
                    }
                }
                if(!$add)
                {
                    foreach($group_by_a as $group_by)
                        $out_a[$in_i][$group_by] = $in[$group_by];
                    foreach($sum_a as $sum)
                        $out_a[$in_i][$sum] = $in[$sum];                    
                }                   
            }

the result:

Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 0
            [s] => 3
        )

    [2] => Array
        (
            [a] => 1
            [b] => 1
            [s] => 2
        )

    [3] => Array
        (
            [a] => 0
            [b] => 1
            [s] => 3
        )

    [5] => Array
        (
            [a] => 1
            [b] => 0
            [s] => 2
        )

)
两仪 2024-11-21 18:39:46

假设您可以将所有数组收集到一个 ie 中:

$arrays = array($array1,$array2,....,$arrayn);

那么

$grouping = array();

foreach($arrays AS $array)
{
   foreach($array['winners'] AS $k=>$v)
   {
      //check if the array key is a number, will contain a team, and if that
      //them is not alreay listed
      if(is_numeric($k) && !array_key_exists($v,$grouping))
         $grouping[$v] = 0;
      //sum the prize to the team's sum
      $grouping[$v] += intval($array['winners']['prizeTotal']);
   }
}
//the following is just for debugging
print_r($grouping);

这应该会产生如下结果:

$grouping[TEAM #1] = 200
$grouping[TEAM #2] = 90
$grouping[CROTCH SNIFFER] = 200
...

Assuming you can collect all your arrays into one i.e. :

$arrays = array($array1,$array2,....,$arrayn);

then

$grouping = array();

foreach($arrays AS $array)
{
   foreach($array['winners'] AS $k=>$v)
   {
      //check if the array key is a number, will contain a team, and if that
      //them is not alreay listed
      if(is_numeric($k) && !array_key_exists($v,$grouping))
         $grouping[$v] = 0;
      //sum the prize to the team's sum
      $grouping[$v] += intval($array['winners']['prizeTotal']);
   }
}
//the following is just for debugging
print_r($grouping);

this should produce something like:

$grouping[TEAM #1] = 200
$grouping[TEAM #2] = 90
$grouping[CROTCH SNIFFER] = 200
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文