PHP - 从对象数组中提取属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1118994/
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
PHP - Extracting a property from an array of objects
提问by abernier
I've got an array of cats objects:
我有一组猫对象:
$cats = Array
(
[0] => stdClass Object
(
[id] => 15
),
[1] => stdClass Object
(
[id] => 18
),
[2] => stdClass Object
(
[id] => 23
)
)
and I want to extract an array of cats' IDs in 1 line (not a function nor a loop).
我想在 1 行中提取一组猫的 ID(不是函数也不是循环)。
I was thinking about using array_walkwith create_functionbut I don't know how to do it.
我正在考虑使用array_walkwithcreate_function但我不知道如何去做。
Any idea?
任何的想法?
回答by Greg
Warning
create_function()has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
create_function()自 PHP 7.2.0 起,警告已被弃用。强烈建议不要依赖此功能。
You can use the array_map()function.
This should do it:
您可以使用该array_map()功能。
这应该这样做:
$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
回答by Josep Alsina
If you have PHP 5.5 or later, the best way is to use the built in function array_column():
如果您有PHP 5.5 或更高版本,最好的方法是使用内置函数array_column():
$idCats = array_column($cats, 'id');
But the son has to be an array or converted to an array
但是儿子必须是数组或者转换成数组
回答by algorhythm
The solution depends on the PHP version you are using. At least there are 2 solutions:
解决方案取决于您使用的 PHP 版本。至少有2个解决方案:
First (Newer PHP versions)
首先(较新的 PHP 版本)
As @JosepAlsina said before the best and also shortest solution is to use array_columnas following:
正如@JosepAlsina 之前所说,最好也是最短的解决方案是使用array_column如下:
$catIds = array_column($objects, 'id');
Notice:For iterating an arraycontaining \stdClasses as used in the question it is only possible with PHP versions >= 7.0. But when using an arraycontaining arrays you can do the same since PHP >= 5.5.
注意:要迭代问题中使用的array包含\stdClasses,它只能使用 PHP 版本>= 7.0。但是当使用array包含arrays 时,你可以做同样的事情,因为 PHP >= 5.5.
Second (Older PHP versions)
第二个(旧的 PHP 版本)
@Greg said in older PHP versions it is possible to do following:
@Greg 说在较旧的 PHP 版本中可以执行以下操作:
$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
But beware:In newer PHP versions >= 5.3.0it is better to use Closures, like followed:
但要注意:在较新的 PHP 版本中>= 5.3.0,最好使用Closures,如下所示:
$catIds = array_map(function($o) { return $o->id; }, $objects);
The difference
区别
First solution creates a new function and puts it into your RAM. The garbage collector does not delete the already created and already called function instance out of memory for some reason. And that regardless of the fact, that the created function instance can never be called again, because we have no pointer for it. And the next time when this code is called, the same function will be created again. This behavior slowly fills your memory...
第一个解决方案创建一个新函数并将其放入您的 RAM 中。由于某种原因,垃圾收集器不会从内存中删除已创建和已调用的函数实例。不管事实如何,创建的函数实例永远不会被再次调用,因为我们没有指向它的指针。下次调用此代码时,将再次创建相同的函数。这种行为会慢慢填满你的记忆......
Both examples with memory output to compare them:
两个示例都带有内存输出来比较它们:
BAD
坏的
while (true)
{
$objects = array_map(create_function('$o', 'return $o->id;'), $objects);
echo memory_get_usage() . "\n";
sleep(1);
}
// the output
4235616
4236600
4237560
4238520
...
GOOD
好的
while (true)
{
$objects = array_map(function($o) { return $o->id; }, $objects);
echo memory_get_usage() . "\n";
sleep(1);
}
// the output
4235136
4235168
4235168
4235168
...
This may also be discussed here
这也可以在这里讨论
Memory leak?! Is Garbage Collector doing right when using 'create_function' within 'array_map'?
回答by SilentGhost
function extract_ids($cats){
$res = array();
foreach($cats as $k=>$v) {
$res[]= $v->id;
}
return $res
}
and use it in one line:
并在一行中使用它:
$ids = extract_ids($cats);
回答by soulmerge
Warning
create_function()has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
create_function()自 PHP 7.2.0 起,警告已被弃用。强烈建议不要依赖此功能。
Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:
PHP 中的内置循环比解释性循环更快,因此将其设为单行循环实际上是有意义的:
$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)
回答by Luke Antins
CODE
代码
<?php
# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);
function extract_ids($array = array())
{
$ids = array();
foreach ($array as $object) {
$ids[] = $object->id;
}
return $ids;
}
$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);
?>
OUTPUT
输出
# var_dump($cats);
array(3) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(15)
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
int(18)
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
int(23)
}
}
# var_dump($cat_ids);
array(3) {
[0]=>
int(15)
[1]=>
int(18)
[2]=>
int(23)
}
I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.
我知道它使用循环,但这是最简单的方法!并且使用一个函数它仍然在一行中结束。
回答by woru
You can do it easily with ouzo goodies
$result = array_map(Functions::extract()->id, $arr);
or with Arrays (from ouzo goodies)
或使用数组(来自茴香酒的好东西)
$result = Arrays::map($arr, Functions::extract()->id);
Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
查看:http: //ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).
另请参阅使用茴香酒进行函数式编程(我无法发布链接)。
回答by Rai Ahmad Fraz
// $array that contain records and id is what we want to fetch a
$ids = array_column($array, 'id');
回答by Kiran Maniya
The create_function()function is deprecated as of php v7.2.0. You can use the array_map()as given,
该create_function()函数自php v7.2.0 起已弃用。你可以使用array_map()给定的,
function getObjectID($obj){
return $obj->id;
}
$IDs = array_map('getObjectID' , $array_of_object);
Alternatively, you can use array_column()function which returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array. You can use the array_column as given,
或者,您可以使用array_column()函数从输入的单个列中返回值,由 column_key 标识。可选地,可以提供 index_key 以通过来自输入数组的 index_key 列的值索引返回数组中的值。您可以使用给定的 array_column,
$IDs = array_column($array_of_object , 'id');
回答by daHormez
$object = new stdClass();
$object->id = 1;
$object2 = new stdClass();
$object2->id = 2;
$objects = [
$object,
$object2
];
$ids = array_map(function ($object) {
/** @var YourEntity $object */
return $object->id;
// Or even if you have public methods
// return $object->getId()
}, $objects);
Output: [1, 2]
输出:[1, 2]

