如果我有一个类型为ArrayCollection的变量,如何检查集合中是否存在具有特定名称的键,包括嵌套。如果是这样,我该如何获取和更改该值呢?
发布于 2016-12-22 17:19:41
我猜你说的是ArrayCollection \Doctrine\Common\Collections\ArrayCollection的教义。
它确实实现了phps原生ArrayAccess接口,所以我们来看看the docs。只需检查如下:
use Doctrine\Common\Collections\ArrayCollection;
$myCollection = new ArrayCollection(array('testKey' => 'testVal'));
var_dump(isset($myCollection['testKey']));它还从Collection接口实现了自己的方法。
/**
* Checks whether the collection contains an element with the specified key/index.
*
* @param string|integer $key The key/index to check for.
*
* @return boolean TRUE if the collection contains an element with the specified key/index,
* FALSE otherwise.
*/
public function containsKey($key);对于嵌套对象,没有build in方法,您必须像使用普通数组一样自己遍历集合。
发布于 2021-11-11 18:09:30
我发现的方法是在ArrayCollection对象中使用toArray()方法,然后使用array_search函数:
$newArray = $arrayCollectionObject->toArray();
$keyThatIneed = array_search($value, $newArray);https://stackoverflow.com/questions/41279306
复制相似问题