doujian4752
doujian4752
2014-04-05 15:01
浏览 25

如何使用php中的值获取数组的索引

<?php
    $interests[50] = array('fav_beverages' => "beer");
?>

now i need the index (i.e. 50 or whatever the index may be) from the value beer.

I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.

please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.

thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer"); $interests[50] = array('fav_cuisine' => "arabic"); $interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpouda6700
    dongpouda6700 2014-04-05 15:08

    If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:

    $needle = 'beer';
    
    foreach ($interests as $index => $arr) {
        foreach ($arr as $value) {
            if ($value == $needle) {
                echo $index;
                break;
            }
        }
    }
    

    Demo

    点赞 评论
  • dongpa5207
    dongpa5207 2014-04-05 15:20

    This should work in your case.

    $interests[50] = array('fav_beverages' => "beer");
    
    function multi_array_search($needle, $interests){
        foreach($interests as $interest){
            if (array_search($needle, $interest)){
                return array_search($interest, $interests);
                break;
            }
        }
    }
    
    echo multi_array_search("beer", $interests);
    
    点赞 评论

相关推荐