简体   繁体   中英

php how to get id of array element

I have an array :

Array ( [0] => Array ( [id] => 10 [name] => Michael [score] => 40 ) [1] => Array ( [id] => 9 [name] => David [score] => 30 ) [2] => Array ( [id] => 8 [name] => David [score] => 20 ) ) 

I want to find id of an element. For example: if i type name = Michael and score = 40 then it will show me id of 0, and so on.

You could use a foreach loop that searches by name and score. The code below searches for Michael with score 40 and populates variable $id with the id found:

$id = null;
foreach($yourArray as $key => $arr) {
    if($arr['name'] == 'Michael' and $arr['score'] == 40) {
        $id = $key;
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM