Re: Help with searching arrays of objects [message #181141 is a reply to message #181139] |
Thu, 18 April 2013 18:10 |
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
|
|
|