dongzhao5834 2012-09-27 08:08
浏览 214
已采纳

如何在php中将对象数组转换为该对象的单个属性的数组?

Say I have an array of Person objects and the person objects have properties firstName, lastName, and age. Now suppose I want an array of the firstnames of all these person objects. How can I convert this array of Person objects into an array of firstname strings?

Is there some combination of array functions I can use to do it or do I just have use a for loop and create a new array?

  • 写回答

4条回答 默认 最新

  • duanji1026 2012-09-27 08:12
    关注

    You can use array_map

        class Person
    {
        public $firstName ;
        public $lastName ;
        public $age ;
    
        function __construct($firstName,$lastName,$age)
        {
            $this->firstName = $firstName ;
            $this->lastName = $lastName ;
            $this->age = $age ;
        }
    }
    
    $list = array();
    $list[] = new Person("John", "Smith", 22);
    $list[] = new Person("Jon", "Doe", 19);
    $list[] = new Person("Jane", "Stack", 21);
    
    $lastNames = array_map(function($var){return $var->lastName ; } ,$list);
    var_dump($lastNames);
    

    Output

    array
      0 => string 'Smith' (length=5)
      1 => string 'Doe' (length=3)
      2 => string 'Stack' (length=5)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名