计算数组中的值,并在数组中添加部分计数和值减法

时间:2014-01-28 09:45:03

标签: php arrays multidimensional-array addition totals

我有这个多维数组,它包含这些内部数组值:

Array_X (
[0] => Array ( [0] => A [1] => D [2] => C [3] =>B ) 
[1] => Array ( [0] => A [1] => D [2] => E )                 
[2] => Array ( [0] => A [1] => E [2] => D )             
[3] => Array ( [0] => D [1] => A [2] => B )     
[4] => Array ( [0] => D [1] => A [2] => C )     
[5] => Array ( [0] => D [1] => E )  
[6] => Array ( [0] => D [1] => E [2] => E [3] =>A ) 
)

在第一个数组中,我在这些数组中的位置[0]中执行“A”和“D”计数。 “A”出现3次,“D”出现4次,并将其存储在另一个1维数组中:

Array_count_1 ( [A] => 3 [D] => 4 )  

然后我从所有这些内部数组中删除“A”(通过“unset”),最后得到:

Array_Y (
[0] => Array ( [0] => **D** [1] => C [2] => B [3] => ) 
[1] => Array ( [0] => **D** [1] => E [2] =>  )              
[2] => Array ( [0] => **E** [1] => D [2] =>  )          
[3] => Array ( [0] => D [1] => B [2] =>  )  
[4] => Array ( [0] => D [1] => C [2] =>  )      
[5] => Array ( [0] => D [1] => E )  
[6] => Array ( [0] => D [1] => E [2] => E [3] =>A )
)

使用第二个新数组,我将需要对出现在第一个元素[0]中的所有值执行计数。在这个新数组(Array_Y)中,“D”计数6次,“E”1次计数位置[0]。

Array_count_2 ( [D] => 6 [E] => 1 ) 

问题:

但是在数组Array_count_2中,而不是给每个D,E等实例赋予一个完整的点,这让我得到了:

Array_count_2 ( [D] => 6 [E] => 1 )

我想为每个实例赋予位置[0]的值(在消除值“A”之后),给出一个部分点(即,例如0.25,而不是计数完成时的默认值1)。

如图所示,在'Array_X'中,当“A”被消除时,值“D”将在2个数组中移位到[0](或2次),并且值“E”将移位到位置[ 0]在1个数组(或1次))。他们的新职位见于'Array_Y'。

而不是:

Array_count_2 ( [D] => 6 [E] => 1 )

我希望数组为:

Array_count_2 ( [D] => 4.50 [E] => 0.25 )

D:阵列'Array_X'中位置[0]的4个点,以及被转移到阵列'Array_Y'中所示的位置[0]的2个点乘以0.25(被授予的部分点)总共的 0.50

E:1点乘以0.25点,转移到位置[0],如数组'Array_Y'所示,总计 0.25

我认为这里的关键在于计算得到:

Array_count_1 ( [A] => 3 [D] => 4 )  

Array_count_2 ( [D] => 6 [E] => 1 ) 

然后:

Array_count_2 - Array_count_1

所以我最终得到了

Array_count_3 ( [D] => 2 [E] => 1 )

我如何执行此减法来获取像'Array_count_3'这样的数组?

然后我需要使用'Array_count_3'并将每个值乘以( 0.25 )得到:

Array_count_4 ( [D] => 0.50 [E] => 0.25 )

然后添加'Array_count_4'+'Array_count_1'

Array_count_1 ( [A] => 3 [D] => 4 )
Array_count_4 ( [D] => 0.50 [E] => 0.25 )

获取FINAL数组:

Array_count_2 ( [D] => 4.50 [E] => 0.25 )

中没有“A”(因为它被删除了)?

感谢您抽出宝贵的时间,并耐心地度过这一切!欣赏它!

1 个答案:

答案 0 :(得分:1)

试试这段代码

foreach ($Array_count_2 as $k => $v) {
    $Array_count_3[$k] = $Array_count_2[$k] - $Array_count_1[$k];
    $Array_count_4[$k] = ($Array_count_2[$k] - $Array_count_1[$k])/0.25;
    $Array_count_2[$k] = $Array_count_4[$k] + $Array_count_1[$k];
}

最后一行覆盖$Array_count_2上的值。使用另一个数组名称保持$Array_count_2原样。