php - 如何将数组与变量值合并
问题描述
我在 Google 上找不到它,或者使用了错误的关键字。如何将变量值“[contestant variable_number -fieldname]”合并到多维数组?
数组示例:
array (
[contestant1-gender] => M
[contestant1-first-name] => Wyatt
[contestant1-last-name] => Heath
[contestant1-occupation] => Ipsa architecto vol
[contestant1-email] => dipuxo@mailinator.com
[contestant1-phone] => +1 (992) 741-8123
[contestant2-gender] => M
[contestant2-first-name] => Leonard
[contestant2-last-name] => Acosta
[contestant2-occupation] => Aut sunt qui offici
[contestant2-email] => sajomogylu@mailinator.com
[contestant2-phone] => +1 (462) 687-8393
[department] => In mollitia impedit
[street] => Sed error magnam obc
[number] => 41
[bus] => In iste ut perspicia
[postalcode] => Commodo impedit vol
[city] => Ad iure veniam veli
[country] => nl
)
对于这样的事情:
Array (
[0] => contestant (
[0] => gender ( )
[1] => first-name ()
)
[1] => contestant (
[0] => gender ( )
[1] => first-name ()
)
[2] => contestant (
[0] => gender ( )
[1] => first-name ()
)
)
解决方案
我认为这至少近似于您正在寻找的内容:
$array = [
'contestant-1-gender' => 'M',
'contestant-1-first-name' => 'Wyatt',
'contestant-1-last-name' => 'Heath',
'contestant-1-occupation' => 'Bl;ah blah',
'contestant-2-gender' => 'M',
'contestant-2-first-name' => 'Leonard',
'contestant-2-last-name' => 'Acosta',
'contestant-2-occupation' => 'Foo',
'department' => 'Who cares?'
];
$contestants = [];
array_walk($array, function($val, $key) use (&$contestants) {
if (preg_match('/contestant\-(?P<id>[\d+])\-(?P<field>.*)/', $key, $matches))
{
$contestants[$matches['id']][$matches['field']] = $val;
}
});
print_r($contestants);
输出:
Array
(
[1] => Array
(
[gender] => M
[first-name] => Wyatt
[last-name] => Heath
[occupation] => Bl;ah blah
)
[2] => Array
(
[gender] => M
[first-name] => Leonard
[last-name] => Acosta
[occupation] => Foo
)
)
推荐阅读
- php - 在 MongoDB 旧版与边缘 (PHP) 上插入文档 ID
- c# - 在 DataGrid WPF 中绑定
- redirect - 我失去了我的域名,有什么办法可以重定向到新网站?
- entity-framework - 如何在 ASP.NET Core 3.1 的另一个应用程序中包含用户管理器
- react-native - 世博会发布后世博会使用字体不起作用
- rxjs - 当您订阅 rxjs 时,如果测试失败,您如何向测试发出信号?
- javascript - 如何从 javascript 获取网络请求列表?
- python - 如何在 azure 中设置 Linux VM,以便我们可以将其作为服务器(不是 apache Web 服务器)进行套接字编程
- c# - 为什么向 ASP.NET Core 3.1 WEB API 或 MVC 控制器的正文中带有 JSON 参数的 Fetch Post 请求没有得到任何东西?
- node.js - 如何处理涉及打字稿的包之间的冲突?