PHP.是否可以将array_column与对象数组一起使用 [英] PHP. Is it possible to use array_column with an array of objects
问题描述
是否可以传递array_column
对象数组?
我已经实现了ArrayAccess接口,但是没有效果.
我应该再实施一个吗?
Is it possible to pass in array_column
an array of objects?
I have implemented ArrayAccess interface, but it has no effect.
Should I implement another one?
class Foo implements ArrayAccess {
public $Id, $Title;
public function offsetExists($offset)
{
return isset($this->{$offset});
}
public function offsetGet($offset)
{
return $this->{$offset};
}
public function offsetSet($offset, $value)
{
$this->{$offset} = $value;
}
public function offsetUnset($offset)
{
unset($this->{$offset});
}
}
$object = new \Foo();
$object->Id = 1;
$object->Title = 'Test';
$records = array(
$object,
array(
'Id' => 2,
'Title' => 'John'
)
);
var_dump(array_column($records, 'Title')); // array (size=1) 0 => string 'John' (length=4)
推荐答案
PHP 5
array_column
不适用于对象数组.使用array_map
代替:
array_column
doesn't work with an array of objects. Use array_map
instead:
$titles = array_map(function($e) {
return is_object($e) ? $e->Title : $e['Title'];
}, $records);
PHP 7
array_column()
该函数现在支持对象数组以及 二维数组.仅考虑公共财产,并且 将
__get()
用于动态属性的对象还必须 实施__isset()
.
The function now supports an array of objects as well as two-dimensional arrays. Only public properties are considered, and objects that make use of
__get()
for dynamic properties must also implement__isset()
.
请参见 https://github.com/php /php-src/blob/PHP-7.0.0/UPGRADING#L629 - 感谢贝尔的提示!
See https://github.com/php/php-src/blob/PHP-7.0.0/UPGRADING#L629 - Thanks to Bell for the hint!
这篇关于PHP.是否可以将array_column与对象数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!