LoginSignup
2
2

More than 5 years have passed since last update.

phpの配列内オブジェクトから特定のメソッドの値を配列で取得

Posted at
array_map(function($obj){return $obj->getId();}, $array);

<?php

class Hi
{
    protected $_id = 0;

    public function getId()
    {
        return $this->_id;
    }

    public function setId($id)
    {
        $this->_id = $id;
    }
}

$hi = new Hi;
$hi3 = clone $hi2 = clone $hi;
$hi->setId(1);
$hi2->setId(2);
$hi3->setId(3);
$hiList = array($hi, $hi2, $hi3);

$map = array_map(function($obj){return $obj->getId();}, $hiList);

var_dump($map);
#array(3) {
#  [0] =>
#  int(1)
#  [1] =>
#  int(2)
#  [2] =>
#  int(3)
#}

もっと簡単な書き方無いかな

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2