[英]PHP how to combine array and create new array
我有 3 个这样的数组:
$first = array(
[0] => 13
[1] => 66
[2] => 15
)
$second = array
(
[0] => append
[1] => prepend
[2] => append
)
$third = array
(
[0] => 2
[1] => 4
[2] => 1
)
现在我想组合这 3 个数组并创建新的SINGLE数组,如下所示:我想从每个数组中获取值并将其合并为一个。
$new_array = array(
[0] = array (
'page'=>13,
'position'=>'append'
'priority'=>'2'
)
[1] = array (
'page'=>66,
'position'=>'prepend'
'priority'=>'4'
)
[2] = array (
'page'=>15,
'position'=>'append'
'priority'=>'1'
)
)
这该怎么做 ?
您可以使用array_map()遍历多个数组(相同长度)并从它们逐项构建一个新数组:
$first = array(13, 66, 15);
$second = array('append', 'prepend', 'append');
$third = array(2, 4, 1);
print_r(
array_map(
function($page, $position, $priority) {
return compact('page', 'position', 'priority');
},
$first,
$second,
$third
)
);
尽管在这种情况下,使用简单的结构 foreach() 可能是另一种选择。
编辑:第 2 版。有些人可能会争辩说,由于可读性和代码可维护性,这更糟。 感谢 AbraCadaver
$keys = ['page', 'position', 'priority'];
// Note: The order in $keys and array_map() arguments must be the same
// On the other hand you only need to type the keys once and it's easy
// to change the number of arguments :)
print_r(
array_map(
function(...$args) use ($keys) {
return array_combine($keys, $args);
},
$first,
$second,
$third
)
);
编辑:版本 3。使用带有箭头函数的稍微现代的 PHP (7.4):
print_r(
array_map(
fn(...$args) => array_combine($keys, $args),
$first,
$second,
$third
)
);
只需映射每个数组的每个元素并返回一个带有键的数组:
$result = array_map(function($f, $s, $t) {
return ['page'=>$f, 'position'=>$s, 'priority'=>$t];
}, $first, $second, $third);
或者在函数之外定义键并与每个元素组合:
$keys = ['page', 'position', 'priority'];
$result = array_map(function($f, $s, $t) use($keys) {
return array_combine($keys, [$f, $s, $t]);
}, $first, $second, $third);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.