dongyi1490
dongyi1490
2012-09-24 08:43

PHP数组:如何获取元素所在的索引

已采纳

Here’s the following array:

Array
(
    [1] => Array
        (
            [0] => 10
            [1] => 13
        )

    [2] => Array
        (
            [0] => 8
            [1] => 22
        )

    [3] => Array
        (
            [0] => 17
            [1] => 14
        )
)

Then I have

$chosenNumber = 17

What I need to know is:

First) if 17 is in the array

Second) the key it has (in this case [0])

Third) the index it belongs (in this case [3])

I was going to use the in_array function to solve first step but it seems it only works for strings ..

Thanks a ton!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • drv16759 drv16759 9年前
    function arraySearch($array, $searchFor) {
        foreach($array as $key => $value) {
            foreach($value as $key1 => $value1) {
                if($value1 == $searchFor) {
                    return array("index" => $key, "key" => $key1);
                }
            }
        }
    
        return false;
    }
    
    print_r(arraySearch($your_array, 17));
    
    点赞 评论 复制链接分享
  • dongzhuo1958 dongzhuo1958 9年前

    array_keys()

    • Return all the keys or a subset of the keys of an array

    array_values()

    • Return all the values of an array

    array_key_exists()

    • Checks if the given key or index exists in the array

    in_array()

    • Checks if a value exists in an array

    You can find more information here http://www.php.net/manual/en/function.array-search.php

    点赞 评论 复制链接分享
  • dow57588 dow57588 9年前

    You should look using these :

    in_array()
    array_search()
    
    点赞 评论 复制链接分享
  • douyi0902 douyi0902 9年前

    You use array_search:

    $index = array_search($chosenNumber, $myArray);
    if($index){
        $element = $myArray[$index];
    }else{
        // element not found
    }
    

    array_search returns false if the element was not found, the index of the element you were looking for otherwise.

    If a value is in the array multiple times, it only returns the key of the first match. If you need all matches you need to use array_keys with the optional search_value parameter specified:

    $indexes = array_keys($myArray, $chosenNumber);
    

    This returns a (possibly empty) array of all indexes containing your search value.

    点赞 评论 复制链接分享
  • duanfeigui6655 duanfeigui6655 9年前

    You have used array_search function

    $qkey=array_search(value,array);
    
    点赞 评论 复制链接分享

相关推荐