0

I have an array with the friends data including their name, id, gender. I want to extract the data from array which have opposite gender. For example - My gender is "Male"

Returned data -

[118]=> object(stdClass)#121 (3) {
    ["name"]=> string(9) "Rawa Su" 
    ["gender"]=> string(4) "male" 
    ["id"]=> string(15) "1000019100" 
} 
[119]=> object(stdClass)#122 (3) {
    ["name"]=> string(11) "Anil Gaj" 
    ["gender"]=> string(4) "male" 
    ["id"]=> string(15) "1000034656" 
} 
[120]=> object(stdClass)#123 (3) {
    ["name"]=> string(13) "Ankur Tri" 
    ["gender"]=> string(4) "male" 
    ["id"]=> string(15) "1000022271" 
} 
[121]=> object(stdClass)#124 (3) {
    ["name"]=> string(13) "Chuck Ell" 
    ["gender"]=> string(4) "male" 
    ["id"]=> string(15) "10000185038" 
} 
[122]=> object(stdClass)#125 (3) {
    ["name"]=> string(15) "Madhuri Tat" 
    ["gender"]=> string(6) "female" 
    ["id"]=> string(15) "1000880932" 
}

Now i want to randomly fetch the data which have gender = female. I don't have any clue how this can be done. Any help would be appreciated. Thank you.

1 Answer 1

2

Okay lets say your array with all of the data is named $data:

$res = array();
foreach($data as $person) {
     if(strcasecmp($person['gender'], 'female') == 0)
          $res[] = $person;
}

Now you have a new array called $res which contains all females.

Nevertheless, i would filter the raw data during the sql fetch from the database, this should be the same effort and give more performance in a long time view.

If you now want to have one of the females randomly, do something like this:

$number_of_persons = count($res);
$random_female = $res[rand(0, $number_of_persons-1)];

Why -1?

Arrays start at index 0, so you need a -1 at the total amount of persons.

Sign up to request clarification or add additional context in comments.

1 Comment

Superb brother ! Thank you so much. God bless you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.