PHP - 从对象数组中提取一列属性

发布于 2024-07-27 15:57:58 字数 485 浏览 6 评论 0原文

我有一个猫对象数组:

$cats = Array
    (
        [0] => stdClass Object
            (
                [id] => 15
            ),
        [1] => stdClass Object
            (
                [id] => 18
            ),
        [2] => stdClass Object
            (
                [id] => 23
            )
)

我想在 1 行中提取猫 ID 数组(不是函数也不是循环)。

我正在考虑将 array_walkcreate_function 一起使用,但我不知道该怎么做。

任何想法?

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).

I was thinking about using array_walk with create_function but I don't know how to do it.

Any idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

白鸥掠海 2024-08-03 15:57:58

如果您有 PHP 7.0 或更高版本,最好的方法是使用内置函数 array_column() 从对象数组中访问属性列

$idCats = array_column($cats, 'id');

:必须是数组或转换为数组

If you have PHP 7.0 or later, the best way is to use the built in function array_column() to access a column of properties from an array of objects:

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array

壹場煙雨 2024-08-03 15:57:58

警告 create_function() 自 PHP 7.2.0 起已弃用。 强烈建议不要依赖此函数。

您可以使用 array_map() 函数。
这应该可以做到:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);

正如 @Relequestual 在下面所写的,该函数现在直接集成在 array_map 中。 新版本的解决方案如下所示:

$catIds = array_map(function($o) { return $o->id;}, $objects);

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

You can use the array_map() function.
This should do it:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);

As @Relequestual writes below, the function is now integrated directly in the array_map. The new version of the solution looks like this:

$catIds = array_map(function($o) { return $o->id;}, $objects);
那片花海 2024-08-03 15:57:58

解决方案取决于您使用的 PHP 版本。 至少有 2 个解决方案:

第一个(较新的 PHP 版本)

正如 @JosepAlsina 之前所说,最好也是最短的解决方案是使用 array_column ,如下所示:

$catIds = array_column($objects, 'id');

注意:
要迭代问题中使用的包含 \stdClasses 的 array,只能使用 PHP 版本 >= 7.0。 但是,当使用包含 arrayarray 时,您可以从 PHP >= 5.5 执行相同的操作。

其次(较旧的 PHP 版本)

@Greg 说在较旧的 PHP 版本中可以执行以下操作:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);

但要注意:在较新的 PHP 版本 >= 5.3.0 中更好使用Closure,如下所示:

$catIds = array_map(function($o) { return $o->id; }, $objects);

区别

使用create_function() 的解决方案创建一个新函数并将其放入 RAM 中。 由于某种原因,垃圾收集器不会从内存中删除已创建和已调用的函数实例。 不管事实如何,创建的函数实例永远不会被再次调用,因为我们没有指向它的指针。 下次调用此代码时,将再次创建相同的函数。 这种行为会慢慢地填满你的记忆...

两个示例都带有内存输出来比较它们:

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
...

while (true)
{
    $objects = array_map(function($o) { return $o->id; }, $objects);

    echo memory_get_usage() . "\n";

    sleep(1);
}

// the output
4235136
4235168
4235168
4235168
...

这也可以在这里讨论

内存泄漏?! 在“array_map”中使用“create_function”时,垃圾收集器是否正确?

The solution depends on the PHP version you are using. At least there are 2 solutions:

First (Newer PHP versions)

As @JosepAlsina said before the best and also shortest solution is to use array_column as following:

$catIds = array_column($objects, 'id');

Notice:
For iterating an array containing \stdClasses as used in the question it is only possible with PHP versions >= 7.0. But when using an array containing arrays you can do the same since PHP >= 5.5.

Second (Older PHP versions)

@Greg said in older PHP versions it is possible to do following:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);

But beware: In newer PHP versions >= 5.3.0 it is better to use Closures, like followed:

$catIds = array_map(function($o) { return $o->id; }, $objects);

The difference

The solution using create_function() 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...

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'?

流星番茄 2024-08-03 15:57:58
function extract_ids($cats){
    $res = array();
    foreach($cats as $k=>$v) {
        $res[]= $v->id;
    }
    return $res
}

并在一行中使用它:

$ids = extract_ids($cats);
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);
如梦 2024-08-03 15:57:58

代码

<?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);

?>

输出

# 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)
}

我知道它使用循环,但这是最简单的方法! 使用函数它仍然会在一行中结束。

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.

夕色琉璃 2024-08-03 15:57:58

您可以使用 ouzo goodies

$result = array_map(Functions::extract()->id, $arr);

或使用数组(来自 ouzo goodies)

$result = Arrays::map($arr, Functions::extract()->id);

轻松完成此操作,请查看:http://ouzo.readthedocs.org/en/latest/utils/functions.html #extract

另请参阅使用茴香酒进行函数式编程(我无法发布链接)。

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

See also functional programming with ouzo (I cannot post a link).

小帐篷 2024-08-03 15:57:58

警告 create_function() 自 PHP 7.2.0 起已弃用。 强烈建议不要依赖此函数。

PHP 中的内置循环比解释循环更快,因此将其设为单行实际上是有意义的:

$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:

$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)
別甾虛僞 2024-08-03 15:57:58
    $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);

输出:[1, 2]

    $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]

余生一个溪 2024-08-03 15:57:58
// $array that contain records and id is what we want to fetch a
$ids = array_column($array, 'id');
// $array that contain records and id is what we want to fetch a
$ids = array_column($array, 'id');
狂之美人 2024-08-03 15:57:58

php v7.2.0 起,create_function() 函数已弃用。 您可以使用给定的 array_map()

function getObjectID($obj){
    return $obj->id;
}

$IDs = array_map('getObjectID' , $array_of_object);

或者,您可以使用 array_column() 函数,该函数返回来自输入的单个列的值,由 column_key 标识。 或者,可以提供一个index_key,以便通过输入数组的index_key 列中的值对返回数组中的值进行索引。 您可以使用给定的 array_column ,

$IDs = array_column($array_of_object , 'id');

The create_function() function is deprecated as of php v7.2.0. You can use the array_map() as given,

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,

$IDs = array_column($array_of_object , 'id');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文