讨论数量:
$post1 = ['张三', '李四', '王五'];
$post2 = ['20岁', '25岁', '40岁'];
$peopleList = [];
foreach ($post1 as $k => $name) {
$people = new stdClass();
$people->name = $name;
$people->title = $post2[$k] ?? '';
$peopleList[] = $people;
}
print_r($peopleList);
$post1 = ['张三', '李四', '王五'];
$post2 = ['20 岁', '25 岁', '40 岁'];
$result = array_map(function($name, $title) {
$obj = new stdClass();
$obj->name = $name;
$obj->title = $title;
return $obj;
}, $post1, $post2);
// 打印结果
print_r($result);
人工智能的回答:
<?php
$post1 = ['张三', '李四', '王五'];
$post2 = ['20 岁', '25 岁', '40 岁'];
// 确保两个数组长度相同
if (count($post1) !== count($post2)) {
throw new Exception("两个数组的长度不相同,无法合并。");
}
// 使用array_map创建新的对象数组
$result = array_map(function($name, $title) {
$obj = new stdClass();
$obj->name = $name;
$obj->title = $title;
return $obj;
}, $post1, $post2);
// 打印结果
print_r($result);
?>
推荐文章: