我需要在php中编写一个脚本,请帮我创建这样的
$a=50;
$b=40;
$c=80;
$d=20;
$e=60;
$total=$a+$b+$c+$d+$e // i.e 250
$avg=($a+$b+$c+$d+$e)/5; //i.e 50
意味着每个元素需要有50个点
我创建了两个数组 i)谁将收到 ii)谁将支付 现在我需要的是显示一条消息
1)$a do not need to give or recieve any point
/* payer */
a)$b need to give 10 points to $e.
b)$d need to give 30 points to $c.
/* payer */
/* reciever*/
a)$c will recieve 30 points from $d.
b)$e will recieve 10 points from $b.
/* reciever*/
现在我被困在如何创建逻辑来显示这样的消息。 请建议我或给我一些想法来帮助你 目前有5个元素可能比它更多(可以是动态的)。
答案 0 :(得分:1)
请找到以下内容,它可能会对您有所帮助:
<?php
/*
$a=50;
$b=40;
$c=80;
$d=20;
$e=80;
$total=$a+$b+$c+$d+$e; // i.e 250
$avg=($a+$b+$c+$d+$e)/5; //i.e 50
*/
// My code start from here
$payer_array = array();
$receiver_array = array();
$element_array = array('a'=>50, 'b'=>40, 'c'=>80, 'd'=>20, 'e'=>50);
$total_element=count($element_array);
$total = array_sum($element_array);
$avg = $total/$total_element;
foreach($element_array as $name=>$payer_value) {
if($payer_value>=$avg) {
$payer_array[$name] = ($payer_value-$avg);
}
else {
$receiver_array[$name] = ($avg-$payer_value);
}
}
foreach ($payer_array as $name=>$payer_value) {
if ($payer_value==0) {
echo "$name do not need to give or receive any point</br>";
}
else {
// exact match
if (in_array($payer_value, $receiver_array)) {
$match_reciever_name = array_search($payer_value, $receiver_array);
echo "$name need to give $payer_value points to $match_reciever_name<br/>";
unset($receiver_array[$match_reciever_name]);
}
// partial match
else {
foreach($receiver_array as $reciever_name=>$reciever_value) {
if($payer_value>0) {
if($reciever_value > $payer_value) {
$recieverd_value = $payer_value;
echo "$name need to give $recieverd_value points to $reciever_name<br/>";
$receiver_array[$reciever_name] = $reciever_value-$recieverd_value;
$payer_value = 0;
if($receiver_array[$reciever_name]==0) {
unset($receiver_array[$reciever_name]);
}
break;
}
else {
$recieverd_value = $reciever_value;
echo "$name need to give $recieverd_value points to $reciever_name<br/>";
unset($receiver_array[$reciever_name]);
$payer_value = $payer_value-$reciever_value;
}
}
}
}
}
}
?>