Bir tuş üzerinde iki dizi birleştirin

1 Cevap php

Ben iki dizi var:

$course =  Array ( [6] => 24 [0] => 20 [1] => 14 ) // etc 

key being the link sonraki diziye ile:

Array ( 
 [0] => Array ( [course_id] => 1 [course_name] => Appetizer ) 
 [1] => Array ( [course_id] => 2 [course_name] => Breakfast )
      ) //etc 

I basically want to add the course_name to the first array on course_id = keyso that it I can print out '1', 'Appetizer', '14' Sorry if Ive explained this badly but its late and merging arrays frazzles my brain at this time!

1 Cevap

Çeşitli yerli dizi yineleme fonksiyonları ile birlikte 5.3 'nin kapatılması oldukça ağrısız bir işlem için bu hale:

<?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"
  }
}
*/