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 ?
Thank you
It's a work for array_map function
$res = array_map(function ($name, $age) { return ['name'=> $name, 'age'=>$age]; },
$names_array, $ages_array);
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.