在 ID 键上有效组合多个关联数组
我有一堆看起来像这样的 php 数组(请不要问为什么,我只是在做我的工作...我要说的是 EAV...):
$firstNames = ([accountId] => 100, [firstName] => 'John'
[accountId] => 101, [firstName] => 'Fred');
$lastNames = ([accountId] => 100, [lastName] => 'Doe'
[accountId] => 101, [lastName] => 'Bloggs');
$city = ([accountId] => 100, [city] => 'New York'
[accountId] => 101, [city] => 'Cambridge');
$country = ([accountId] => 100, [country] => 'USA'
[accountId] => 101, [country] => 'UK');
等等等等。
我必须将它们组合成一个array:
$userDetails = ([accountId] => 100, [firstName] => "John", [lastName] => "Doe",
[city] => "New York", [country] => "USA");
我的感觉是,正确的答案是将这些属性从 EAV 中分离出来并正确建模。但我不能。也可以在数据库中的自连接上进行自连接,但是我简化了示例,这实际上是不可能的 - 而且我被告知要这样做......可能有一堆稍后还会添加其他字段。
那么,在 PHP 中生成一个关联数组并合并 accountId 的最佳方法是什么?有没有一个函数,或者我需要一圈又一圈等等。
I have a bunch of php arrays that look like this (please don't ask why, I'm just doing my job...All I will say is EAV...):
$firstNames = ([accountId] => 100, [firstName] => 'John'
[accountId] => 101, [firstName] => 'Fred');
$lastNames = ([accountId] => 100, [lastName] => 'Doe'
[accountId] => 101, [lastName] => 'Bloggs');
$city = ([accountId] => 100, [city] => 'New York'
[accountId] => 101, [city] => 'Cambridge');
$country = ([accountId] => 100, [country] => 'USA'
[accountId] => 101, [country] => 'UK');
etc etc.
I have to combine them into one array:
$userDetails = ([accountId] => 100, [firstName] => "John", [lastName] => "Doe",
[city] => "New York", [country] => "USA");
My feeling is the correct answer would be to break these attributes out of EAV and model them correctly. But I can't. It would also be possible to do self-join upon self-join in the db, but I have simplified the example and this is not really possible - and I've been told to do it this way...There could be a bunch of additional fields tacked on as well, later.
So what is the best way to produce one associative array, merging on accountId in PHP? Is there a function, or do I need to loop round and round etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个嵌套的
foreach
应该可以做到:查看它的工作
This nested
foreach
should do it:See it working