用PHP的D'Hondt方法计算器?

时间:2016-03-06 20:41:06

标签: php xml

大家好我的项目有问题,让我解释一下。我可以将数据拖到xml文件中,但无法通过D'Hondt方法读取分配的座位数。我试了很多次但是做不到。有人可以给我任何帮助吗?

这是我的代码

$i = 0;
foreach ($xml->city as $city) {
    echo '<tr><th>';
    echo $xml->city[$i]->attributes(). "</th>";
    echo '<th>Votes</th><th>Seats:';
    echo $city->total_seats.'</th></tr>';
    foreach ($xml->city[$i]->party_votes as $party_votes) {
            foreach ($party_votes as $party_votes) {
                echo '<tr style="color:'.$color[$i].'"><td>';
                echo $party_votes->attributes()."</td><td> ";
                echo $citya[$i]=$party_votes->total_votes. "</td>";
            }
    }
    $i++;
    echo "</tr>";
}

这是xml文件

 <city id="City A">
	  <total_seats>8</total_seats>
	  <party_votes>
		<party id ="Party A">
			<total_votes>100000</total_votes>
		</party>
		<party id ="Party B">
			<total_votes>80000</total_votes>
		</party>
		<party id ="Party C">
			<total_votes>30000</total_votes>
		</party>
		<party id ="Party D">
			<total_votes>20000</total_votes>
		</party>
	  </party_votes>
   </city>
   <city id="City B">
	  <total_seats>6</total_seats>
	  <party_votes>
		<party id ="Party A">
			<total_votes>10000</total_votes>
		</party>
		<party id ="Party B">
			<total_votes>50000</total_votes>
		</party>
		<party id ="Party C">
			<total_votes>40000</total_votes>
		</party>
		<party id ="Party D">
			<total_votes>30000</total_votes>
		</party>
	  </party_votes>
   </city>   

如何实施D'Hondt方法为Php中的投票分配席位?

1 个答案:

答案 0 :(得分:1)

从xml文档中提取值并生成D'Hondt分布是两个独立的问题。我会专注于后者。 以下是使用generator functionSplPriorityQueue的示例。

<?php
function gen_dhondt(array $results) {
    // using SplPriorityQueue as a sorted listed
    $foo = new SplPriorityQueue;
    $foo->setExtractFlags(SplPriorityQueue::EXTR_DATA);
    // initialize the list
    foreach( $results as $party=>$votes ) {
        $foo->insert(['name'=>$party, 'div'=>1, 'votes'=>$votes], $votes);
    }

    // get the element with the highest votes/divisor
    foreach( $foo as $next ) {
        // re-enqueue this element with ++divisor
        ++$next['div'];
        $foo->insert($next, $next['votes']/$next['div']);

        // "return" the name of this element
        yield $next['name'];
    }
}


$seats = 8;
$results = array('C'=>30000, 'B'=>80000, 'A'=>100000, 'D'=>20000);

// a) just show the order in which the seats are distributed
$lit = new LimitIterator( gen_dhondt($results), 0, $seats);
foreach( $lit as $p ) {
    echo $p, "\r\n";
}

// b) count the seats
var_export(
    array_count_values(
        iterator_to_array(
            new LimitIterator( gen_dhondt($results), 0, $seats)
        )
    )
);

打印

A
B
A
B
A
C
B
A
array (
  'A' => 4,
  'B' => 3,
  'C' => 1,
)

(请记住a)和b)是两个完全独立的运行;如果你想要可以以更有效的方式组合它们 - 但是这个例子并没有针对效率进行优化....)