首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从PHP数组生成一定数量的数据?

如何从PHP数组生成一定数量的数据?
EN

Stack Overflow用户
提问于 2016-04-21 21:00:19
回答 1查看 30关注 0票数 2

我试图从一个PHP数组中生成一个列表,当用户输入一个数字,比如3,那么数组中每个元素的总数将只显示3个。

示例:

代码语言:javascript
复制
$number_to_generate = 3;
jobs = array('Academic', 'Administrator', 'Architect',.......);

Output:
Academic
Academic
Academic
Administrator
Administrator
Administrator    
Architect
Architect
Architect

这就是我目前的情况:

代码语言:javascript
复制
// 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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-21 21:02:46

如果我能正确理解你想要的,那就很容易做了。

代码语言:javascript
复制
//  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;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36780376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档