基于用户输入的加权数组

时间:2014-08-26 23:24:19

标签: php arrays

我试图允许用户创建一个索引数组,然后将其添加到与其关联的百分比的数组中。这是一个例子:

EX1

$pages[] = array('index1.php','25');
$pages[] = array('index2.php','25');
$pages[] = array('index3.php','50');

EX2

$pages[] = array('index1.php','25');
$pages[] = array('index2.php','75');

甚至

EX3

$pages[] = array('index1.php','25');
$pages[] = array('index2.php','25');
$pages[] = array('index3.php','25');
$pages[] = array('index4.php','25');

我想创建一个包含以下内容的文件:

OUTPUT EX1

index1.php
index2.php
index3.php
index3.php

OUTPUT EX2

index1.php
index2.php
index2.php
index2.php

OUTPUT EX3

index1.php
index2.php
index3.php
index4.php

我只需取$ page [] [1]的总和除以数组中的项数吗?

3 个答案:

答案 0 :(得分:2)

如果您不介意冗余,只需列出文件重量给出的次数。 例如,您将列出index1.php(25/25)次(1)和index3.php(50/25)次(2)。

答案 1 :(得分:2)

得到最小数字,然后除以它,然后使用str_repeat。 (我不知道什么是更好的方式。)示例代码:

$pages[] = array('index1.php','25');
$pages[] = array('index2.php','25');
$pages[] = array('index3.php','25');
$pages[] = array('index4.php','25');

$min = min(array_map(function($weight){
    return $weight[1];
}, $pages));

foreach($pages as $page) {
    echo str_repeat($page[0] . '<br/>', $page[1] / $min);
}

答案 2 :(得分:0)

其实我不同意答案,假设你有

$pages[] = array('index1.php','10');
$pages[] = array('index2.php','20');
$pages[] = array('index3.php','40');
$pages[] = array('index4.php','35');

然后你的输出将是:

index1.php
index2.php
index2.php
index3.php
index3.php
index3.php
index3.php
index4.php
index4.php
index4.php

此输出错误。如你所见,我们在这里有index4次。

要计算正确的值,您应该使用最大公约数。例如:

/*
* function gcd()
* 
* returns greatest common divisor
* between two numbers
* tested against gmp_gcd()
*/
function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

/*
* function gcd_array()
* 
* gets greatest common divisor among
* an array of numbers
*/
function gcd_array($array, $a = 0)
{
    $b = array_pop($array);
    return ($b === null) ?
        (int)$a :
        gcd_array($array, gcd($a, $b));
}

$array = [10,20,40,35];
$result = gcd_array($array);

for ($i = 0; $i < sizeof($array); $i++)
{
  echo $array[$i] / $result;
  echo "\r\n";
}

在这种情况下输出将是:

2 4 8 7

(index1 - 2次,index2 - 4次,索引3 - 8次,index4 - 7次)

并且我认为这是正确的。