【问题标题】:How to join two arrays by putting one at the end of each array?如何通过在每个数组的末尾放置一个来连接两个数组?
【发布时间】:2021-12-30 08:57:28
【问题描述】:

我有两个这样的数组:

$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的末尾

非常感谢大家。

【问题讨论】:

  • 这些语法错误是因为你使用了翻译器吗?
  • 是的,我用了翻译器,对不起

标签: php arrays merge


【解决方案1】:

此解决方案可以帮助您:

$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"
  }
}

如果你想测试,这是代码的链接:http://sandbox.onlinephpfunctions.com/code/a8548fff9271c76d9c8b57a2c6baee93fcad0e01

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    你可以这样实现:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多