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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?