是否可以传入array_column
一个对象数组?
我已经实现了ArrayAccess接口,但它没有效果.
我应该再实施一个吗?
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)
Run Code Online (Sandbox Code Playgroud)
Dan*_* W. 113
PHP 5
array_column
不适用于对象数组.array_map
改为使用:
$titles = array_map(function($e) {
return is_object($e) ? $e->Title : $e['Title'];
}, $records);
Run Code Online (Sandbox Code Playgroud)
PHP 7
array_column()
该函数现在支持对象数组和二维数组.仅考虑公共属性,并且
__get()
还必须实现用于动态属性的对象__isset()
.
请参阅https://github.com/php/php-src/blob/PHP-7.0.0/UPGRADING#L629 - 感谢Bell的提示!
是否可以在array_column中传入一个对象数组?
PHP 7
是的,请参阅http://php.net/manual/en/function.array-column.php
PHP 5> = 5.5.0
在PHP 5 array_column
中不适用于对象数组.您可以尝试:
// object 1
$a = new stdClass();
$a->my_string = 'ciao';
$a->my_number = 10;
// object 2
$b = new stdClass();
$b->my_string = 'ciao b';
$b->my_number = 100;
// array of objects
$arr_o = array($a,$b);
// using array_column with an array of objects
$result = array_column(array_map(function($o){return (array)$o;},$arr_o),'my_string');
Run Code Online (Sandbox Code Playgroud)
PS:为了清楚起见,我更喜欢不使用array_column
和使用带有匿名函数的array_map
$result = array_map(function($o){ return $o->my_string; }, $arr_o);
Run Code Online (Sandbox Code Playgroud)
或者简单 foreach
$result = array();
foreach($arr_o as $o) {
$result[] = $o->my_string;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
34817 次 |
最近记录: |