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

如何使用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 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

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?