【问题标题】:How to generate a certain amount from PHP array?如何从 PHP 数组中生成一定数量的?
【发布时间】:2016-04-21 21:00:19
【问题描述】:

我正在尝试从 PHP 数组中生成一个列表,当用户输入一个数字 3 时,该数组中的每个元素总共只会显示 3 个。

例子:

$number_to_generate = 3;
jobs = array('Academic', 'Administrator', 'Architect',.......);

Output:
Academic
Academic
Academic
Administrator
Administrator
Administrator    
Architect
Architect
Architect

这是我目前拥有的:

// Check if tmp_profession_array is empty
// If it is empty grab any random profession and add it to the tmp_profession_array
array_filter($tmp_profession_array);
if (empty($tmp_profession_array)) {
    $Profession = array_rand($professions_array, 1);
    $tmp_profession_array[$Profession] = 1;
} else {
    // If it is not empty, grab the last profession from it
    end($tmp_profession_array);
    $Profession = key($tmp_profession_array);
    //// If it is not less than the amount to generate grab a new profession that does not exist in the tmp_profession_array
    if ($tmp_profession_array[$Profession] > $number_to_generate) {
        $break = TRUE;
        while ($break) {
            if (in_array($Profession, $tmp_profession_array)) {
                $Profession = array_rand($professions_array, 1);
            } else {
                $break = FALSE;
            }
        }
    //// If the profession count is less than the amount to generate then use it
    } elseif ($tmp_profession_array[$Profession] < $number_to_generate) {
        $tmp_profession_array[$Profession] += 1;
    }
}

【问题讨论】:

  • 哇 :) 你是如何实现这个实现的?

标签: php arrays loops


【解决方案1】:

如果我正确理解你想要什么,这很容易做到。

//  How many times you want to see each job?
$numberToGenerate = 3;

//  List of jobs you have
$jobs = array('Academic', 'Administrator', 'Architect');

//  Loop on all the jobs
foreach($jobs as $job){
    //  Loop $numberToGenerate times
    for($i=0; $i < $numberToGenerate; $i++){
        //  Echo to output
        echo $i.'-'.$job.'<br />';
    }
}

//  Done
exit;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 2011-07-03
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多