Get index of element in an array by the value

前端 未结 5 1213
-上瘾入骨i
-上瘾入骨i 2020-12-28 15:01

I have this array in PHP:

array(
    [0] => array( \'username\' => \'user1\' )
    [1] => array( \'username\' => \'user2\' )
)

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 15:53

    If you have a 2D array, like in your example, you'll need to customise things a little:

    function array_search2d($needle, $haystack) {
        for ($i = 0, $l = count($haystack); $i < $l; ++$i) {
            if (in_array($needle, $haystack[$i])) return $i;
        }
        return false;
    }
    
    $myArray = array(
        array( 'username' => 'user1' ),
        array( 'username' => 'user2' )
    );
    $searchTerm = "user1";
    
    if (false !== ($pos = array_search2d($searchTerm, $myArray))) {
        echo $searchTerm . " found at index " . $pos;
    } else {
        echo "Could not find " . $searchTerm;
    }
    

    If you wanted to search in just one particular field, you could alter the function to something like this:

    function array_search2d_by_field($needle, $haystack, $field) {
        foreach ($haystack as $index => $innerArray) {
            if (isset($innerArray[$field]) && $innerArray[$field] === $needle) {
                return $index;
            }
        }
        return false;
    }
    

提交回复
热议问题