Today in this tutorial we are going to merge two different arrays into single associative array in PHP.
Last time i was creating travel based website and creating own engine in which the condition holiday package was to merge two different array of title an description into single array.
To know the clear example on what i am saying is that “title” was in one array and “description” was in another array similar to given example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$titles = array( 'Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6' ); $descriptions = array( 'Day One Itinerary Description', 'Day Two Itinerary Description', 'Day Three Itinerary Description', 'Day Four Itinerary Description', 'Day Five Itinerary Description', 'Day Six Itinerary Description' ); |
Out target is to merge the both arrays into one as title and description.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
Array ( [0] => Array ( [title] => Day 1 [description] => Day One Itinerary Description ) [1] => Array ( [title] => Day 2 [description] => Day Two Itinerary Description ) [2] => Array ( [title] => Day 3 [description] => Day Three Itinerary Description ) [3] => Array ( [title] => Day 4 [description] => Day Four Itinerary Description ) [4] => Array ( [title] => Day 5 [description] => Day Five Itinerary Description ) [5] => Array ( [title] => Day 6 [description] => Day Six Itinerary Description ) ) |
So what we are going to do loop through the first array and then use the key of first array to arrange the correct title and description in order.
Lets create the function to merge and sort them properly.
1 2 3 4 5 6 7 8 9 10 |
function mergeArrays($titles, $descriptions) { $result = array(); foreach ( $titles as $key=>$title ) { $result[] = array( 'title' => $title, 'description' => $descriptions[$key]); } return $result; } $data = mergeArrays($titles,$descriptions); |
Here you go, just var_dump()
or print_r()
to know the result.
Leave a Reply