PHP中如何将两个数组合并为指定格式的单一数组?
Hey there! I get it—you tried using array_merge() but it just wasn't giving you the paired, formatted array you wanted. That's totally expected, since array_merge() simply appends one array to the end of the other instead of matching up elements by their positions. Let's go through a couple of straightforward ways to get your desired result.
Method 1: Use array_map() (Cleanest Approach)
This is the most concise way to pair elements from two arrays and format them. The array_map() function can accept multiple arrays, and its callback will receive the corresponding element from each array at each iteration:
$array_1 = [1, 2, 3, 4]; $array_2 = ["a", "b", "c", "d"]; // Pair and concatenate elements $array_3 = array_map(function($number, $letter) { return "$number $letter"; }, $array_1, $array_2); // Output: Array ( [0] => 1 a [1] => 2 b [2] => 3 c [3] => 4 d ) print_r($array_3);
If your arrays might be of different lengths, array_map() will stop at the shortest one—so you won't get errors from missing elements.
Method 2: Use a foreach Loop (More Control)
If you need extra control (like handling cases where one array is longer than the other), a foreach loop works great. We'll loop through the first array and use its index to grab the matching element from the second array:
$array_1 = [1, 2, 3, 4]; $array_2 = ["a", "b", "c", "d"]; $array_3 = []; foreach ($array_1 as $index => $number) { // Only add a pair if the second array has an element at this index if (isset($array_2[$index])) { $array_3[] = "$number {$array_2[$index]}"; } } print_r($array_3);
This lets you add custom logic—like skipping missing elements or adding a default value if one array is shorter.
Why array_merge() Didn't Work
Just to clarify: array_merge($array_1, $array_2) would give you [1, 2, 3, 4, "a", "b", "c", "d"]—it combines the arrays sequentially, not by pairing corresponding elements. That's why it wasn't the right tool for this job!
内容的提问来源于stack exchange,提问作者za1782852

