我有一个数组,我想在其中搜索uid并获得数组的键。

例子

假设我们有以下二维数组:

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    )
);

函数调用search_by_uid(100)(第一个用户的uid)应该返回0。

函数调用search_by_uid(40489)应该返回2。

我试着做循环,但我想要一个更快的执行代码。


当前回答

如果问题,即。

$a = [
     [
       "_id" => "5a96933414d48831a41901f2",
       "discount_amount" => 3.29,
       "discount_id" => "5a92656a14d488570c2c44a2",
     ],
     [
       "_id" => "5a9790fd14d48879cf16a9e8",
       "discount_amount" => 4.53,
       "discount_id" => "5a9265b914d488548513b122",
     ],
     [
       "_id" => "5a98083614d488191304b6c3",
       "discount_amount" => 15.24,
       "discount_id" => "5a92806a14d48858ff5c2ec3",
     ],
     [
       "_id" => "5a982a4914d48824721eafe3",
       "discount_amount" => 45.74,
       "discount_id" => "5a928ce414d488609e73b443",
     ],
    [
       "_id" => "5a982a4914d48824721eafe55",
       "discount_amount" => 10.26,
       "discount_id" => "5a928ce414d488609e73b443",
     ],
   ];

岁:

function searchForId($id, $array) {
    $did=0;
    $dia=0;
   foreach ($array as $key => $val) {
       if ($val['discount_id'] === $id) {
           $dia +=$val['discount_amount'];
           $did++;
       }
   }
    if($dia != '') {
        echo $dia;
        var_dump($did);
    }
   return null;
};
print_r(searchForId('5a928ce414d488609e73b443',$a));

其他回答

在Jakub的出色回答的基础上,这里有一个更通用的搜索,将允许指定键(不仅仅是uid):

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}

用法:$results = searcharray('searchvalue', searchkey, $array);

我想检查下面的数组$arr是否有'abc'存在于子数组中

$arr = array(
    array(
        'title' => 'abc'
    )
);

然后我可以用这个

$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
    echo 'exists';
} else {
    echo 'notExists';
}

我认为这是最简单的定义方式

这里有一个更好的解决方案,如果您从数据库或多维数组中提取数据

多维数组的例子:

$records = array(
            array(
                'id' => 2135,
                'first_name' => 'John',
                'last_name' => 'Doe',
            ),
            array(
                'id' => 3245,
                'first_name' => 'Sally',
                'last_name' => 'Smith',
            ),
            array(
                'id' => 5342,
                'first_name' => 'Jane',
                'last_name' => 'Jones',
            ),
            array(
                'id' => 5623,
                'first_name' => 'Peter',
                'last_name' => 'Doe',
            )
            );


            function search_user_by_name($name, $array) {
                             foreach ($array as $keys) {
                                 foreach ($keys as $key => $_user_record) {
                                     if ($_user_record == $name) {
                                         return [$key => $_user_record];//Return and array of user
                                     }
                                 }
                             }
                             return null;
                        }

调用函数:

$results = search_user_by_name('John', $records);
         print_r($results);
         

输出:Array ([first_name] => John)

试试这个

<?php
 function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && 
            recursive_array_search($needle,$value) !== false)) {
             return $current_key;
        }
    }
    return false;
 }
 ?>

我知道这个问题已经回答了,但我在代码中使用了这个问题并对其进行了扩展,这样就不需要只根据uid进行搜索了。我只是想把它分享给其他可能需要这个功能的人。

这是我的例子,请记住这是我的第一个答案。我去掉了参数数组,因为我只需要搜索一个特定的数组,但是您可以很容易地将它添加进去。我想要搜索的不仅仅是uid。

此外,在我的情况下,由于其他字段的搜索结果可能不是唯一的,可能有多个键要返回。

 /**
     * @param array multidimensional 
     * @param string value to search for, ie a specific field name like name_first
     * @param string associative key to find it in, ie field_name
     * 
     * @return array keys.
     */
     function search_revisions($dataArray, $search_value, $key_to_search) {
        // This function will search the revisions for a certain value
        // related to the associative key you are looking for.
        $keys = array();
        foreach ($dataArray as $key => $cur_value) {
            if ($cur_value[$key_to_search] == $search_value) {
                $keys[] = $key;
            }
        }
        return $keys;
    }

后来,我写了这个,以允许我搜索另一个值和关联键。因此,我的第一个示例允许您在任何特定的关联键中搜索值,并返回所有匹配的值。

第二个例子显示了在某个关联键(first_name)中找到一个值('Taylor'),在另一个关联键(hired)中找到另一个值(true),并返回所有匹配(名字为'Taylor'并且被雇用的人的键)。

/**
 * @param array multidimensional 
 * @param string $search_value The value to search for, ie a specific 'Taylor'
 * @param string $key_to_search The associative key to find it in, ie first_name
 * @param string $other_matching_key The associative key to find in the matches for employed
 * @param string $other_matching_value The value to find in that matching associative key, ie true
 * 
 * @return array keys, ie all the people with the first name 'Taylor' that are employed.
 */
 function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
    // This function will search the revisions for a certain value
    // related to the associative key you are looking for.
    $keys = array();
    foreach ($dataArray as $key => $cur_value) {
        if ($cur_value[$key_to_search] == $search_value) {
            if (isset($other_matching_key) && isset($other_matching_value)) {
                if ($cur_value[$other_matching_key] == $other_matching_value) {
                    $keys[] = $key;
                }
            } else {
                // I must keep in mind that some searches may have multiple
                // matches and others would not, so leave it open with no continues.
                $keys[] = $key;
            }
        }
    }
    return $keys;
}

函数的使用

$data = array(
    array(
        'cust_group' => 6,
        'price' => 13.21,
        'price_qty' => 5
    ),
    array(
        'cust_group' => 8,
        'price' => 15.25,
        'price_qty' => 4
    ),
    array(
        'cust_group' => 8,
        'price' => 12.75,
        'price_qty' => 10
    )
);

$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);

结果

Array ( [0] => 2 )