2012-03-24 33 views
2

我正在嘗試爲我的童子軍隊伍創建一份工作名單,而且我正在生成一份工作問題。在一個數組中循環前進的項目

我有一個數組,其中包含爲人民的工作。然後,我使用循環顯示與某個人相關的工作。

有什麼辦法可以讓我的工作提高一個嗎?

例如:

Person 1  -  Job 1 
Person 2  -  Job 2 
Person 3  -  Job 3 

這則轉到:

Person 1 -  Job 2 
Person 2 -  Job 3 
Person 3 -  Job 1 

然後

Person 1 -  Job 3 
Person 2 -  Job 2 
Person 3 -  Job 1 

但是因爲用戶可以改變一個組中的人數(從2 - 20),我怎麼能在沒有硬編碼的情況下讓這個過程發生?

+0

我不太肯定什麼嘗試。我已經看到了當前,下一個,以前的陣列的東西,但我甚至不知道這是否可以幫助我。我已經得到了比人們更多的工作(簡單檢查是否有人比工作更多,增加更多工作,說沒有工作,並且下降到2人,並且硬編碼在一起工作) – ixchi 2012-03-24 02:44:58

回答

1

從我可以告訴你,你想循環的工作,同時保持人員固定。

如果是這樣的話,你可以在1個循環做到這一點:

<?php 

$persons = array(

'Person 1' =>  'Job 1', 
'Person 2' =>  'Job 2' , 
'Person 3' =>  'Job 3' 

); 

//Get the 'persons' 
$keys = array_keys($persons); 

//Get the 'jobs' 
$jobs = array_values($persons); 

foreach ($i = 0; $i < count($keys); $i++){ 

    //Remove first value and reinsert it to the end of the array 
    $firstValue = array_shift($jobs); 
    $jobs[] = $firstValue; 

    //Add the keys back to the array 
    $result = array_combine($keys, $jobs); 
    var_dump($result); //Do whatever you want to the result here. 
} 
+0

這似乎很好。我將如何去循環我的$ names數組中的數據和我的$ jobs數組到$ persons數組中? – ixchi 2012-03-24 03:01:50

+0

你的意思是你想把'$ names'和'$ jobs'結合到一個名爲'$ persons'的關聯數組中嗎?如果是這種情況,請使用'$ persons = array_combine($ names,$ jobs);' – F21 2012-03-24 03:05:30

+0

是的。謝謝,這已經解決了我的問題。 – ixchi 2012-03-24 03:24:18

0

你有兩個不同的數組?一個爲一個人,另一個爲工作?如果是這種情況,我將循環訪問person數組,然後在作業數組中循環與person數組相同的次數(從0開始並每次遞增)。假設人員和工作是平等的。如果你澄清我可能會有的任何問題,我可以改變我的答案。

For i = 0 to i = person_array.length - 1 
    For j = 0 to j = person_array.length - 1 
     int k = j // to show the starting point for the job so first time through job 1, second job 2, etc 
     print person_array[i] " - " job_array[k] 
     if k = job_array.length then j = 0 // starts at the beginning or the job array 
    end for 
end for 
+0

我不確定那是什麼語言,或者如何將其轉換爲PHP。 – ixchi 2012-03-24 02:50:09

1
  • 把第一元件在臨時變量
  • 通過一個循環運行陣列和陣列的當前元素設置爲下一個
  • 陣列的最後一個元素設置爲臨時變量
+0

我試過這個,它對我來說好像不太好。循環中的代碼將數組的下一個元素設置爲上面的代碼是什麼? – ixchi 2012-03-24 03:04:28

0
<?php 

$array = array('one' => '1', 'two' => '2', 'three' => '3', 'four' => '4'); 

$keys = array_keys($array); 
$vals = array_values($array); 

$vals[] = array_shift($vals); 

$new = array_combine($keys, $vals); 

print_r($new); 

?> 

輸出:

Array 
(
    [one] => 2 
    [two] => 3 
    [three] => 4 
    [four] => 1 
) 
相關問題