5.3's closures combined with the various native array iteration functions make this in to a pretty painless process:
<?php
// where $key is a course_id and $value is the associated course's next course
$nextCourse = array(6 => 24, 0 => 20, 1 => 14);
// course definitions
$courses = array(
0 => array("course_id" => 1, "course_name" => 'Appetizer'),
1 => array("course_id" => 2, "course_name" => 'Breakfast')
);
// loop through and add a next_course reference if one exists in $nextCourse map
foreach($courses as &$course) {
if (isset($nextCourse[$course["course_id"]])) {
$course["next_course"] = $nextCourse[$course["course_id"]];
}
}
// $courses is now the same as the var dump at the end
/**
* A bit of 5.3 proselytism with native array functions and closures, which is
* an overly complex answer for this particular question, but a powerful pattern.
*
* Here we're going to iterate through the courses array by reference and
* make use of a closure to add the next course value, if it exists
*
* array_walk iterates over the $courses array, passing each entry in
* the array as $course into the enclosed function. The parameter is
* marked as pass-by-reference, so you'll get the modifiable array instead
* of just a copy (a la pass-by-value). The enclosure function requires
* the 'use' keyword for bringing external variables in to scope.
*/
array_walk($courses, function(&$course) use ($nextCourse) {
/**
* We check to see if the current $course's course_id is a key in the
* nextCourse link mapping, and if it is we take the link mapping
* value and store it with $course as its next_course
*/
if (isset($nextCourse[$course["course_id"]])) {
$course["next_course"] = $nextCourse[$course["course_id"]];
}
});
var_dump($courses);
/**
Output:
array(2) {
[0]=>
array(3) {
["course_id"]=>
int(1)
["course_name"]=>
string(9) "Appetizer"
["next_course"]=>
int(14)
}
[1]=>
array(2) {
["course_id"]=>
int(2)
["course_name"]=>
string(9) "Breakfast"
}
}
*/