我有两个数组:
$course = Array ( [6] => 24 [0] => 20 [1] => 14 ) // etc
将键作为链接到下一个数组:
Array (
[0] => Array ( [course_id] => 1 [course_name] => Appetizer )
[1] => Array ( [course_id] => 2 [course_name] => Breakfast )
) //etc
我基本上想要将course_name添加到course_id = key
上的第一个数组,以便我可以打印'1', 'Appetizer', '14'
对不起,如果我已经解释得很糟糕,但它的晚期和合并阵列在这个时候让我的大脑眩晕!
答案 0 :(得分:1)
5.3的闭包与各种本机数组迭代函数相结合,使得这个过程非常简单:
<?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"
}
}
*/