7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オブジェクトに対して、オブジェクトを後ろに追加したい

Posted at

まあたまには、PHPで連想配列じゃなくてオブジェクトをごにょることもあるさ。そんなときオレは、オブジェクトの個数を数えたくなったんだ。

array_push()だとか、$obj[] = $objなんかはすべて配列用だ。うーん、数えたいだけなんだけどなァ!

ってときは new ArrayObject()して空のArrayObjectを作ろう。
これにより、->append()メソッドが使えるようになる。ここにぶち込めば、その名の通り後ろに追加してくれる。

//$objects = 10個ぐらいで、
//$objects->name = 'unko' は3個としよう

$push = new ArrayObject();
foreach( $objects as $object ){
  if( $object->name == 'unko' ){
    $push->append( $object );
  }
}
count($push); // -> 3

ふうすっきり

7
7
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?