PHP-从对象数组中提取属性 [英] PHP - Extracting a property from an array of objects

查看:735
本文介绍了PHP-从对象数组中提取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列猫对象:

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

,我想在1行中提取猫的ID数组(而不是函数或循环).

and I want to extract an array of cats' IDs in 1 line (not a function nor a loop).

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

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

有什么主意吗?

推荐答案

如果您具有 PHP 5.5或更高版本,最好的方法是使用内置函数array_column():

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

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

但是儿子必须是数组或转换为数组

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

这篇关于PHP-从对象数组中提取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆