php 返回一个数组中特定值的所有下标

参考文档     http://php.net/manual/zh/function.array-keys.php


首个下标  array_search 

多个下标   array_keys 配合可选参数 search_value 完成 

eg:  


function showIndex($source_arr, $sum)
{
    $index_list = [];
    $pass_index_list = [];
    foreach ($source_arr as $index => $value) {

        // filter repeat index
        if (in_array($value, $pass_index_list)) {
            continue;
        }

        // search another index
        $diff = $sum - $value;
        $ano_index = array_keys($source_arr, $diff);

        if (!$ano_index) {
            continue;
        }

       foreach ($ano_index as $choose_index) {
           $index_list[] = [$index,$choose_index];
       }


        // set repeat index
        $pass_index_list[] = $diff;

    }

    return $index_list;
}


// run function
$source_arr = [49, 1, 2, 3, 50, 50,49,49, 51];
//$source_arr = [49, 1, 2, 3, 50, 51];
$sum = 99;

print_r(showIndex($source_arr, $sum));

你可能感兴趣的:(php)