[英]Merge two arrays into one associative array
I have two arrays that I want to merge into one associative array. 我有两个要合并为一个关联数组的数组。 My first array looks like this:
我的第一个数组如下所示:
$names_array = ["John", "Paul", "George"];
The second one looks like this: 第二个看起来像这样:
$ages_array = [26, 29, 22];
I would like to merge these two arrays and obtain this structure: 我想合并这两个数组并获得此结构:
$members_infos = [{"name": "John", "age": 26}, {"name": "Paul", "age":
29}, {"name": "George", "age": 22}];
Do I have to use a for loop in order to achieve what I want or can use a php function ? 我是否必须使用for循环才能实现我想要的功能或可以使用php函数?
Thank you 谢谢
By using array combine function you can join names, ages 通过使用数组合并功能,您可以连接名称,年龄
$names_array = ["John", "Paul", "George"];
$ages_array = [26, 29, 22];
$result = [];
$members_infos = array_combine($names_array,$ages_array);
foreach ($members_infos as $key => $value) {
$result[] = ['name'=>$key, 'age'=>$value];
}
$output = json_encode($result);
echo "<pre>";
print_r($output);
echo "</pre>";
exit;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.