php 在给定属性值的对象数组中查找数组键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4166198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find array key in objects array given an attribute value
提问by el_quick
I have an objects array like this:
我有一个这样的对象数组:
Array
(
[945] => member Object
(
[id] => 13317
[name] => Test 999
[last_name] => Test 999
)
[54] => member Object
(
[id] => 13316
[name] => Manuel
[last_name] => Maria parra
)
[654] => member Object
(
[id] => 13315
[name] => Byron
[last_name] => Castillo
)
[656] => member Object
(
[id] => 13314
[name] => Cesar
[last_name] => Vasquez
)
)
I need to remove one of these objects according to an attribute value.
For example, I want to remove from the array the object id 13316.
我需要根据属性值删除这些对象之一。
例如,我想从数组中删除对象 id 13316。
回答by erisco
Here is the functional approach:
这是函数式方法:
$neededObjects = array_filter(
$objects,
function ($e) {
return $e->id != 13316;
}
);
回答by Jacob Relkin
function filter_by_key($array, $member, $value) {
$filtered = array();
foreach($array as $k => $v) {
if($v->$member != $value)
$filtered[$k] = $v;
}
return $filtered;
}
$array = ...
$array = filter_by_key($array, 'id', 13316);
回答by Gordon
Since there is already plenty solutions given, I suggest an alternative to using the array:
由于已经给出了很多解决方案,我建议使用数组的替代方法:
$storage = new SplObjectStorage; // create an Object Collection
$storage->attach($memberObject); // add an object to it
$storage->detach($memberObject); // remove that object
You could make this into a custom MemberCollection
class with Finder methods and other utility operations, e.g.
您可以MemberCollection
使用 Finder 方法和其他实用程序操作将其制作为自定义类,例如
class MemberCollection implements IteratorAggregate
{
protected $_storage;
public function __construct()
{
$this->_storage = new SplObjectStorage;
}
public function getIterator()
{
return $this->_storage;
}
public function addMember(IMember $member)
{
$this->_storage->attach($member);
}
public function removeMember(IMember $member)
{
$this->_storage->detach($member);
}
public function removeBy($property, $value)
{
foreach ($this->_storage as $member) {
if($member->$property === $value) {
$this->_storage->detach($member);
}
}
}
}
Might be overkill for your scenario though.
不过对于你的场景来说可能有点矫枉过正。
回答by Govind Samrow
Use array search function :
使用数组搜索功能:
//return array index of searched item
$key = array_search($search_value, array_column($list, 'column_name'));
$list[key]; //return array item
回答by bcosca
foreach ($array as $key=>$value)
if ($value->id==13316) {
unset($array[$key]);
break;
}