FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Help with searching arrays of objects
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Help with searching arrays of objects [message #181141 is a reply to message #181139] Thu, 18 April 2013 18:10 Go to previous messageGo to previous message
Denis McMahon is currently offline  Denis McMahon
Messages: 634
Registered: September 2010
Karma:
Senior Member
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
}

--
Denis McMahon, denismfmcmahon(at)gmail(dot)com
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: display two values on page
Next Topic: Problema con variables de sesion...
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Wed Nov 27 11:53:26 GMT 2024

Total time taken to generate the page: 0.04105 seconds