2016-04-21 12 views
2

私はPHP配列からリストを生成しようとしています。ユーザーが数字を入力すると3となり、配列内の各要素の合計が3つだけ表示されます。PHP配列から一定量を生成するには?

例:

// 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; 
    } 
} 
+0

Wow :)この実装にはどのようになったのですか? –

答えて

3

行うのは非常に簡単に私はあなたが欲しいものを正しく理解している場合:

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

Output: 
Academic 
Academic 
Academic 
Administrator 
Administrator 
Administrator  
Architect 
Architect 
Architect 

は、これは私が現在持っているものです。

// 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; 
関連する問題