gpt4 book ai didi

php - 使用 ArrayCollection::map 创建关联数组

转载 作者:行者123 更新时间:2023-12-03 19:33:02 25 4
gpt4 key购买 nike

TL;DR:为什么 Doctrine 的 ArrayCollection 只支持映射数组而不设置键?

我想从我的 Doctrine 实体创建一个关联数组(键-> 值):即 customerId => CustomerName , userId => userName等。创建关联数组不是火箭科学,因此有许多其他方法可以实现这一点。

但是,我仍然想知道为什么ArrayCollection:map (或类似的方法)没有这样做的选项。它的构造方法和 ArrayCollection::set() 支持使用键创建数组。 .你甚至可以像这样创建一个数组:

$arraycollection = new ArrayCollection();
$arraycollection->add('John Doe');
$arraycollection->set('foo', 'bar');
$arraycollection->set(418, 'teapot');

但是你不能用 ArrayCollection::map() 设置 key .为什么?我是第一个正在寻找这样的功能的开发人员(不太可能)还是我错过了一个重要的原则,使它变得不必要、不可能、不受欢迎或不好的做法?

最佳答案

我在 Adam Wathan 的博客中找到了这个答案 Customizing Keys When Mapping Collections :

This problem of wanting to customize keys during a map operation is something I get asked about pretty regularly.

I think the reason it seems like a tricky problem is because in PHP, we use the same data type to represent both a list and a dictionary.



他使用 Laravel 的 Collection 库:
$emailLookup = $employees->reduce(function ($emailLookup, $employee) {
$emailLookup[$employee['email']] = $employee['name'];
return $emailLookup;
}, []);

这正是我想使用的解决方案,但它不在 Doctrine 的 ArrayCollection 中。 pull request由于向后兼容,已关闭添加 reduce() 方法。

感谢 this example ,您可以基于 Doctrine 的 ArrayCollection 实现自己的类:
use Doctrine\Common\Collections\ArrayCollection;

class ExtendedArrayCollection extends ArrayCollection
{
/**
* Reduce the collection into a single value.
*
* @param \Closure $func
* @param null $initialValue
* @return mixed
*/
public function reduce(\Closure $func, $initialValue = null)
{
return array_reduce($this->toArray(), $func, $initialValue);
}
}

关于php - 使用 ArrayCollection::map 创建关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36955808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com