Filtering arrays based on an object attribute

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • laredotornado@zipmail.com

    Filtering arrays based on an object attribute

    Hi,

    I have an array filled with a particular type of object, which
    contains an attribute "m_level", of integer type. What I want is to
    get a subset of the array whose "m_level" attribute is equal to zero.
    Is there a short way I can do this other than iterating through a
    foreach / for loop?

    I'm using PHP 4.4.4.

    Thanks, - Dave

  • OmegaJunior

    #2
    Re: Filtering arrays based on an object attribute

    On Tue, 27 Feb 2007 23:23:14 +0100, laredotornado@z ipmail.com
    <laredotornado@ zipmail.comwrot e:
    Hi,
    >
    I have an array filled with a particular type of object, which
    contains an attribute "m_level", of integer type. What I want is to
    get a subset of the array whose "m_level" attribute is equal to zero.
    Is there a short way I can do this other than iterating through a
    foreach / for loop?
    >
    I'm using PHP 4.4.4.
    >
    Thanks, - Dave
    >
    Did you try the array_filter() function?


    --
    Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

    Comment

    • Sjoerd

      #3
      Re: Filtering arrays based on an object attribute

      laredotornado@z ipmail.com wrote:
      Hi,
      >
      I have an array filled with a particular type of object, which
      contains an attribute "m_level", of integer type. What I want is to
      get a subset of the array whose "m_level" attribute is equal to zero.
      Is there a short way I can do this other than iterating through a
      foreach / for loop?
      >
      I'm using PHP 4.4.4.
      >
      Thanks, - Dave
      >

      function filter_particul ar_type($array) {
      $result = array();
      foreach ($array as $item) {
      if ($item->m_level == 0) {
      $result[] = $item;
      }
      }
      return $result;
      }

      // or

      function callback_filter ($item) {
      return $item->m_level == 0;
      }
      array_filter($a rray, 'callback_filte r');

      Comment

      Working...