[英]Is it possible to use array_merge_recursive without assoc keys?
Given that I have the request data below:鉴于我有以下请求数据:
$request = [
'name' => ['John Doe', 'Jane Doe', 'Janie Doe'],
'email' => ['john@doe.com', 'jane@doe.com', 'janie@doe.com'],
'password' => ['john123', 'jane123', 'janie123'],
];
I want to make it look like this:我想让它看起来像这样:
array:3 [▼
0 => array:3 [▼
0 => "John Doe"
1 => "john@doe.com"
2 => "john123"
]
1 => array:3 [▼
0 => "Jane Doe"
1 => "jane@doe.com"
2 => "jane123"
]
2 => array:3 [▼
0 => "Janie Doe"
1 => "janie@doe.com"
2 => "janie123"
]
]
When I use array_merge_recursive();当我使用 array_merge_recursive();
$result = array_merge_recursive($request['name'], $request['email'], $request['password']);
The $result
looks like this. $result
看起来像这样。
array:9 [▼
0 => "John Doe"
1 => "Jane Doe"
2 => "Janie Doe"
3 => "john@doe.com"
4 => "jane@doe.com"
5 => "janie@doe.com"
6 => "john123"
7 => "jane123"
8 => "janie123"
]
However, when I add a prefix to all of my values like so:但是,当我像这样为我的所有值添加前缀时:
$request = [
'name' => [
'user_0' => 'John Doe',
'user_1' => 'Jane Doe',
'user_2' => 'Janie Doe',
],
'email' => [
'user_0' => 'john@doe.com',
'user_1' => 'jane@doe.com',
'user_2' => 'janie@doe.com',
],
'password' => [
'user_0' => 'john123',
'user_1' => 'jane123',
'user_2' => 'janie123',
],
];
This same code below gives me a very different result.下面的相同代码给了我一个非常不同的结果。
$result = array_merge_recursive($request['name'], $request['email'], $request['password']);
Which looks like this:看起来像这样:
array:3 [▼
"user_0" => array:3 [▼
0 => "John Doe"
1 => "john@doe.com"
2 => "john123"
]
"user_1" => array:3 [▼
0 => "Jane Doe"
1 => "jane@doe.com"
2 => "jane123"
]
"user_2" => array:3 [▼
0 => "Janie Doe"
1 => "janie@doe.com"
2 => "janie123"
]
]
So, if I were to loop through my request and prefix the keys, I can simply use array_merge_recursive()
.因此,如果我要遍历我的请求并为键添加前缀,我可以简单地使用
array_merge_recursive()
。 But then it's redundant since I am already looping my request values and can simply assign them to a hand made $results
during the loop.但这是多余的,因为我已经在循环我的请求值,并且可以在循环期间简单地将它们分配给手工制作的
$results
。
Is there a secret to make array_merge_recursive()
just work as I want it to?有什么秘诀可以让
array_merge_recursive()
像我想要的那样工作吗?
Using array_map()
, you can get it to combine the arrays if you pass in null as the callback, from the manual...使用
array_map()
,如果你传入 null 作为回调,你可以得到它来组合 arrays,来自手册......
NULL can be passed as a value to callback to perform a zip operation on multiple arrays. If only array1 is provided, array_map() will return the input array.
NULL可以作为一个值传递给回调,对多个arrays执行zip操作。如果只提供array1,array_map()将返回输入数组。
$result = array_map(null, $request['name'], $request['email'], $request['password']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.