Forum Moderators: coopster

Message Too Old, No Replies

Sweeping arrays

         

asantos

9:04 pm on Dec 17, 2006 (gmt 0)

10+ Year Member



Hi. I have this array:

$a[0]['name'] = 'john';
$a[1]['name'] = 'kate';
$a[2]['name'] = 'mary';

i need a way to:
1) check which of the sub-arrays has the name=='kate'
2) get the array index to access other data ($a[x])

Thanks.
andres

eelixduppy

9:11 pm on Dec 17, 2006 (gmt 0)



1)

Something like this should work:


function Get_Index($name,$array) {
return [url=http://us3.php.net/manual/en/function.array-search.php]array_search[/url](array('name'=>$name),$array);
}

2)

This returns the numerical key of the first array, so then you would just do this:


$array = $a[Get_Index('kate',$a)];
echo '<pre>';
print_r($array);
echo '</pre>';

Good luck! :)

asantos

9:41 pm on Dec 17, 2006 (gmt 0)

10+ Year Member



it worked perfectly!
thanks for the quick reply.

andres

asantos

11:22 pm on Dec 17, 2006 (gmt 0)

10+ Year Member



eelixduppy, sorry to ask again, your code did work. but i forgot to mention that the $a array had several subkeys, like this:

$a[0]['name'] = 'kate';
$a[0]['lastname'] = 'riemann';
$a[1]['name'] = 'john';
$a[1]['lastname'] = 'smith';
$a[2]['name'] = 'mary';
$a[2]['lastname'] = 'santos';

$c = array_search(array('name'=>'john'),$a);
echo $c;

$c is not returning any value.

what I need is value '1' (so i know $a[1] is the right one).

What should i implement to your original function in order to get the proper key?

eelixduppy

11:53 pm on Dec 17, 2006 (gmt 0)



I decided to change the approach a little :)

function Get_Array($name,$array) {
foreach($array as $person) {
if($person['name'] == $name) {
return $person;
}
}
return FALSE;
}

$a[0]['name'] = 'kate';
$a[0]['lastname'] = 'riemann';
$a[1]['name'] = 'john';
$a[1]['lastname'] = 'smith';
$a[2]['name'] = 'mary';
$a[2]['lastname'] = 'santos';

echo '<pre>';
print_r(Get_Array('john',$a));
echo '</pre>';

asantos

4:03 am on Dec 18, 2006 (gmt 0)

10+ Year Member



as you say, different approach, but it works ok!