2011-04-06 49 views
2

我有2個陣列的長度相同。陣列$gPositionStudents和陣列$gPositionInternships。每個學生都被分配到不同的實習,這部分工作。沒有indexOfOutBounds的換檔陣列

現在我想$gPositionStudent的第一個元素(索引0)引用數組$gPositionInternship的第二個(索引1)元素。這隱含意味着$gPositionStudents的最後一個元素指的是$gPositionInternship的第一個元素。 (我包括了我的解釋圖片)。

我的代碼是:

// Make table 
$header = array(); 
$header[] = array('data' => 'UGentID'); 
$header[] = array('data' => 'Internships'); 
// this big array will contains all rows 
// global variables. 
global $gStartPositionStudents; 
global $gStartPositionInternships; 
//var_dump($gStartPositionInternships); 
$rows = array(); 
$i = 0; 
foreach($gStartPositionStudents as $value) { 
    foreach($gStartPositionInternships as $value2) { 
     // each loop will add a row here. 
     $row = array(); 
     // build the row 
     $row[] = array('data' => $value[0]['value']);    
     //if($value[0] != 0 || $value[0] == 0) { 
     $row[] = array('data' => $gStartPositionInternships[$i]);   
    } 
    $i++; 
    // add the row to the "big row data (contains all rows) 
    $rows[] = array('data' => $row); 
} 
$output = theme('table', $header, $rows); 
return $output; 

現在我想,我可以選擇多少次,我們可以轉移。 1班或2班或更多班。我想要什麼在PHP中存在?

回答

2

事情是這樣的:

//get the array keys for the interns and students... 
$intern_keys = array_keys($gStartPositionInternships); 
$student_keys = array_keys($gStartPositionStudents); 

//drop the last intern key off the end and pin it to the front. 
array_unshift($intern_keys, array_pop($intern_keys)); 

//create a mapping array to join the two arrays together. 
$student_to_intern_mapping = array(); 
foreach($student_keys as $key=>$value) { 
    $student_to_intern_mapping[$value] = $intern_keys[$key]; 
} 

你需要對其進行修改以滿足您的代碼的其餘部分,但希望這將證明你可以使用的技術。注意這裏的關鍵線是array_unshift()array_pop()。代碼中的評論應該解釋它在做什麼。

+0

完美,謝謝您的回覆! – user001 2011-04-06 13:58:02

1

我想你想要做array_slice($gPositionsStudents, 0, X)其中X是要移動的移動次數。這片數的數組元素。然後執行array_merge($gPositionsStudents, $arrayOfSlicedOfPositions);將這些添加到原始數組的末尾。

然後你可以做一個array_combine從兩個數組中創建一個key =>值對的數組。

+0

感謝您的回覆! – user001 2011-04-06 19:06:43