Re: Help with searching arrays of objects [message #181143 is a reply to message #181141] |
Thu, 18 April 2013 18:29 |
The Natural Philosoph
Messages: 993 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 18/04/13 19:10, Denis McMahon wrote:
> On Thu, 18 Apr 2013 08:35:27 -0700, daveh wrote:
>
>> On Thursday, April 18, 2013 9:24:50 AM UTC-4, Jerry Stuckle wrote:
>>> On 4/17/2013 8:47 PM, daveh(at)allheller(dot)net wrote:
>>>> Hello,
>>>> I know this has probably been asked before but I'm still a bit of a
>>>> noob.
>>>> Given the following structure I need a way to get a "key" to the
>>>> desired object using a members value.
> Simplifying your array
>
>>>> Array
>>>> (
>>>> [0] => gnp Object
>>>> (
>>>> [m_name] => db_1
>>>> )
>>>> [1] => gnp Object
>>>> (
>>>> [m_name] => db_2
>>>> )
>>>> )
>>>> So I need a method to find the objects key using m_name's value.
>>> About the only thing you can do is use a foreach() loop to step through
>>>
>>> the array items, comparing m_name in each object to the desired value,
>>> i.e.
>>>
>>> for ($mylist as $key => $item) {
>>> if ($item->m_name = $desired_value) {
>>> // $key will contain the index of the desired item here
>>> Additionally, if these are class objects, you should study up on object
>>> oriented techniques; your data should be private and you should have
>>> access methods to get and set the values. This ensures validity of the
>>> objects at all times.
>> Yeah I know its still a work in progress.
> Assuming you have access to the code that defines a gnp class, add a
> method such as:
>
> public function get_name() {
> return $this->m_name;
> }
>
> Then, building on Jerry's foreach, if you just want to get the index
> value ($key) or the class member ($item) for the first (only, if you're
> sure there's only ever one) match:
>
> foreach ($mylist as $key => $item)
> if ($item->get_name() == $desired_value)
> break;
>
> // $key will contain the index of the desired item here
> // and $item will contain the actual item
>
> however if you want to process every matching element of the array in
> some way:
>
> foreach ($mylist as $key => $item)
> if ($item->get_name() == $desired_value) {
> // do something here with the $key or $item
> }
>
I suspect that key value pairs are hashed/indexed in some way in PHP as
foreach loops seem to run very much faster than I expected even on large
arrays.
--
Ineptocracy
(in-ep-toc’-ra-cy) – a system of government where the least capable to lead are elected by the least capable of producing, and where the members of society least likely to sustain themselves or succeed, are rewarded with goods and services paid for by the confiscated wealth of a diminishing number of producers.
|
|
|