php - 基于用户输入的加权数组

标签 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');

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

输出 EX1

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

输出 EX2

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

输出 EX3

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

我可以将 $page[][1] 的总和除以数组中的项目数吗?

最佳答案

只需获取最小数字,然后将其除以该数字,然后使用 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);
}

关于php - 基于用户输入的加权数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25516682/

相关文章:

php - JQUERY自动完成获取id而不是值

c - 我在生成随机数时遇到问题 (C)

arrays - 在 Erlang 中对数组数组进行排序

php - 我无法获取 api V3 php 中最后修改的 gSuite-Table

php - 如何在 PHP 分页中继续保留 sql 结果中的行数?

php - 这个 MySQL 查询语法有什么问题?

arrays - 逐行解析数组并将其分解为更多数组

C: 数组下标低于数组边界

arrays - 使用 lodash 将对象数组转换为数组对象

php - 在 CodeIgniter 中用别名值(文章标题)替换 URI 参数(文章 ID)