繁体   English   中英

将两个数组合并为一个,相应地合并数据

[英]Merge two arrays in one, combining the data correspondingly

有了这两个数组,它们分别具有完全相同的项数(3)和分别对应的数据,我如何将它们合并到一个唯一的数组中,如我在数组3示例中所示那样合并数据

// array 1
[ ▼ 3 items
  {
    "email": "john-doe@example.tld"
  },
  {
    "email": "joe-bloggs@example.tld"
  },
  {
    "email": "foo-bar@example.tld"
  }
]

// array 2
[ ▼ 3 items
  {
    "name": "John Doe"
  },
  {
    "name": "Joe Bloggs"
  },
  {
    "name": "Foo Bar"
  }
]

我如何将它们合并成这样:

// array 3
[ ▼ 3 items
  {
    "name": "John Doe",
    "email": "john-doe@example.tld"
  },
  {
    "name": "Joe Bloggs",
    "email": "joe-bloggs@example.tld"
  },
  {
    "name": "Foo Bar",
    "email": "foo-bar@example.tld"
  }
]

我正在使用laravel php。 我已经尝试了array_merge($array1, $array2)和一些laravel的函数$res = $array1->merge($array2); 但我无法获得想要的结果。

array_merge不合并元素,它只是将数组相互连接。

您可以使用array_map() array_merge()在每对元素上调用array_merge()

$result = array_map('array_merge', $array1, $array2);

使用Laravel的Combine()方法

$collection = collect(['name', 'email']);
for($i=0;$i<count($array1);$i++){
$combined[] = $collection->combine([$array2[$i],$array1[$i]]);
}
$combined->all();

或只是使用收藏

$collection = collect($array1, $array2);

我不知道您的输入数据是什么样子,所以我不得不做一些假设。 想法是遍历所有电子邮件,在电子邮件数组中占据其位置,然后使用该位置定义名称在名称数组中的名称。

$emails = [
    ["email" => "john-doe@example.tld"], 
    ["email" => "joe-bloggs@example.tld"], 
    ["email" => "foo-bar@example.tld"]
];

$names = [
    ["name" => "John Doe"],
    ["name" => "Joe Bloggs"],
    ["name" => "Foo Bar"]
];

$names_and_emails = [];

foreach ($emails as $key => $email) {
    $names_and_emails[] = ["email" => $email['email'], "name" => $names[$key]['name']];
}

var_dump($names_and_emails);

输出:

array(3) {
  [0]=>
  array(2) {
    ["email"]=>
    string(20) "john-doe@example.tld"
    ["name"]=>
    string(8) "John Doe"
  }
  [1]=>
  array(2) {
    ["email"]=>
    string(22) "joe-bloggs@example.tld"
    ["name"]=>
    string(10) "Joe Bloggs"
  }
  [2]=>
  array(2) {
    ["email"]=>
    string(19) "foo-bar@example.tld"
    ["name"]=>
    string(7) "Foo Bar"
  }
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM