如何通过在每个数组的末尾放置一个来连接两个数组?

How to join two arrays by putting one at the end of each array?

我有两个这样的数组:

$a = array (1 => [
                       1 => "a",
                       2 => "b",
                       3 => "c"]
                    2 => [
                        1 => "d",
                        2 => "e",
                        3 => "f"]
                    3 => [
                        1 => "g",
                        2 => "h",
                        3 => "i"]);

$b = array (1 => "1", 2 => "2", 3 => "3");

我需要两个数组如下

$a = array (1 => [
                       1 => "a",
                       2 => "b",
                       3 => "c",
                       4 => 1]
                    2 => [
                        1 => "d",
                        2 => "e",
                        3 => "f",
                        4 => 2]
                    3 => [
                        1 => "g",
                        2 => "h",
                        3 => "i",
                        4 => 3]
);

这样两个数组合并,数组$b的元素保留在数组$a

的末尾

非常感谢大家。

你可以这样实现:

foreach ($a as $key => $value) {
    if (isset($b[$key])) $a[$key][count($a[$key]) + 1] = $b[$key];
}

解释:

  • 我们迭代我们的 $a 数组
  • $key是其当前数组的索引
  • 我们确保只添加来自 $b 的元素(如果它存在)以避免错误
  • 我们将正确的元素添加到 $a[$key]count($a[$key]) + 1 索引处,因为计数是 3,计数 + 1 是 4

此解决方案可以帮助您:

$a = [
    1 => [
        1 => "a",
        2 => "b",
        3 => "c"
    ],
    2 => [
        1 => "d",
        2 => "e",
        3 => "f"
    ],
    3 => [
        1 => "g",
        2 => "h",
        3 => "i"
    ]
];

$b = [
    1 => "1", 
    2 => "2", 
    3 => "3"
];

$result = [];
array_walk($a, function($item, $key, $b) use (&$result) {
    $result[$key] = array_merge($item, (array) $b[$key]);
}, $b);

本解var_dump

array(3) {
  [1]=>
  array(4) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
    [3]=>
    string(1) "1"
  }
  [2]=>
  array(4) {
    [0]=>
    string(1) "d"
    [1]=>
    string(1) "e"
    [2]=>
    string(1) "f"
    [3]=>
    string(1) "2"
  }
  [3]=>
  array(4) {
    [0]=>
    string(1) "g"
    [1]=>
    string(1) "h"
    [2]=>
    string(1) "i"
    [3]=>
    string(1) "3"
  }
}

这是一个link的代码,如果你想测试的话:http://sandbox.onlinephpfunctions.com/code/a8548fff9271c76d9c8b57a2c6baee93fcad0e01

希望对您有所帮助。