Connecting Tech Pros Worldwide Help | Site Map

Filtering arrays based on an object attribute

  #1  
Old February 27th, 2007, 10:35 PM
laredotornado@zipmail.com
Guest
 
Posts: n/a
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

  #2  
Old February 27th, 2007, 10:55 PM
OmegaJunior
Guest
 
Posts: n/a

re: Filtering arrays based on an object attribute


On Tue, 27 Feb 2007 23:23:14 +0100, laredotornado@zipmail.com
<laredotornado@zipmail.comwrote:
Quote:
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/
  #3  
Old February 27th, 2007, 11:05 PM
Sjoerd
Guest
 
Posts: n/a

re: Filtering arrays based on an object attribute


laredotornado@zipmail.com wrote:
Quote:
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_particular_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($array, 'callback_filter');
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Performance tuning atlaste answers 13 May 11th, 2007 09:45 PM
CSharp Coding Standards auratius@gmail.com answers 19 April 3rd, 2007 03:35 PM
What is Expressiveness in a Computer Language Xah Lee answers 669 July 22nd, 2006 04:45 PM
author index for Python Cookbook 2? Andrew Dalke answers 10 July 19th, 2005 12:26 AM