PHP多维数组按值搜索

时间:2022-10-28 16:15:01

I have an array where I want to search the uid and get the key of the array.

我有一个数组,我想要搜索uid并获取数组的键。

Examples

Assume we have the following 2-dimensional array:

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

$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'
    )
);

The function call search_by_uid(100) (uid of first user) should return 0.

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

The function call search_by_uid(40489) should return 2.

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

I tried making loops, but I want a faster executing code.

我尝试了循环,但是我想要一个更快的执行代码。

20 个解决方案

#1


327  

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

这将工作。你应该这样称呼它:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

重要的是要知道,如果您使用的是=== =运算符比较类型,则必须完全相同,在本例中,您必须搜索字符串或仅使用==替换=== =。

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

基于angoru回答。在PHP的后续版本(>= 5.5.0)中,可以使用一行代码。

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

这是文档:http://php.net/manual/en/function.array-column.php。

#2


202  

If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.

如果您正在使用(PHP 5 >= 5.5.0),您不需要编写自己的函数来实现这一点,只需编写这一行就可以了。

If you want just one result:

如果你只想要一个结果:

$key = array_search(40489, array_column($userdb, 'uid'));

For multiple results

对多个结果

$keys = array_keys(array_column($userdb, 'uid'), 40489);

In case you have an associative array as pointed in the comments you could make it with:

如果你有一个关联数组,你可以在评论中指出:

$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);

If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!

如果您正在使用PHP < 5.5.0,您可以使用这个后台端口,谢谢ramsey!

Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!

更新:我已经做了一些简单的基准测试,多结果表单似乎是最快的,甚至比Jakub自定义函数还要快!

#3


22  

Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

基于Jakub出色的答案,这里有一个更通用的搜索,它将允许指定的键(不只是uid):

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

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

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

#4


13  

I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.

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

Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.

这是我的例子,请记住这是我的第一个答案。我取出了param数组,因为我只需要搜索一个特定的数组,但是您可以轻松地添加它。我想要搜索的不仅仅是uid。

Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.

此外,在我的情况下,可能会有多个键返回,因为其他字段可能不是惟一的。

 /**
     * @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;
    }

Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.

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

This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).

第二个示例向您展示在某个关联键(first_name)中找到一个值('Taylor'),在另一个关联键(used)中找到另一个值(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;
}

Use of function

使用的函数

$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);

Result

结果

Array ( [0] => 2 ) 

#5


8  

I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:

我在description函数array_search下面修改了一个示例。函数searchItemsByKey从多维数组(N层)返回所有值(s)。也许,这对某些人是有用的。例子:

 $arr = array(
     'XXX'=>array(
               'YYY'=> array(
                    'AAA'=> array(
                          'keyN' =>'value1'
                   )
               ),
              'ZZZ'=> array(
                    'BBB'=> array(
                          'keyN' => 'value2'
                   )
               )
              //.....
           )
);


$result = searchItemsByKey($arr,'keyN');

print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
  [0] => value1
  [1] => value2
)

Function code:

函数代码:

function searchItemsByKey($array, $key)
{
   $results = array();

  if (is_array($array))
  {
    if (isset($array[$key]) && key($array)==$key)
        $results[] = $array[$key];

    foreach ($array as $sub_array)
        $results = array_merge($results, searchItemsByKey($sub_array, $key));
  }

 return  $results;
}

#6


5  

In later versions of PHP (>= 5.5.0) you can use this one-liner:

在PHP的后续版本(>= 5.5.0)中,您可以使用以下一行:

$key = array_search('100', array_column($userdb, 'uid'));

#7


4  

Looks array_filter will be suitable solution for this...

看起来array_filter将适合这个…

$userdb=Array
(
    (0) => Array
        (
            (uid) => '100',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

PHP Code

PHP代码

<?php 
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
  return $v['uid'] => $search;
}) 

$values= print_r(array_value($found)); 
$keys =  print_r(array_keys($found)); 

#8


3  

Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.

虽然这是一个老问题,而且有一个公认的答案,但我还是建议你改变一下接受的答案。首先,我同意大家接受的答案是正确的。

function searchArrayKeyVal($sKey, $id, $array) {
   foreach ($array as $key => $val) {
       if ($val[$sKey] == $id) {
           return $key;
       }
   }
   return false;
}

Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.

用函数中的参数替换预设的“uid”,因此现在调用下面的代码意味着可以跨多个数组类型使用一个函数。很小的改变,但是有一点不同。

    // Array Data Of Users
$userdb = array (
    array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
    array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
    array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);

// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
    echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
    echo "Search Result can not be found";
}

PHP Fiddle Example

PHP小提琴的例子

#9


1  

I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:

我必须使用un函数来查找数组中的每个元素。所以我修改了函数由Jakub Truneček遵循:

function search_in_array_r($needle, $array) {
    $found = array();
    foreach ($array as $key => $val) {
        if ($val[1] == $needle) {
            array_push($found, $val[1]);
        }
    }
    if (count($found) != 0)
        return $found;
    else
        return null;
}

#10


1  

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

#11


1  

you can use this function ; https://github.com/serhatozles/ArrayAdvancedSearch

你可以用这个函数;https://github.com/serhatozles/ArrayAdvancedSearch

<?php 
include('ArraySearch.php');

$query = "a='Example World' and b>='2'";

$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);

$Result = ArraySearch($Array,$query,1);

echo '<pre>';
print_r($Result);
echo '</pre>'; 

// Output:
// Array
// (
//    [0] => Array
//        (
//            [a] => Example World
//            [b] => 2
//        )
//
// )

#12


1  

$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

$found = null;
$search = 'eee';

array_walk($a, function ($k, $v) use ($search, &$found) {
    if (in_array($search, $k)) {
        $found = $v;
    }
});

var_dump($found);

#13


1  

Here is one liner for the same,

这是一个相同的内线,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];

#14


0  

Try this also

试试这个也

function search_in_array($srchvalue, $array)
{
    if (is_array($array) && count($array) > 0)
    {
        $foundkey = array_search($srchvalue, $array);
        if ($foundkey === FALSE)
        {
            foreach ($array as $key => $value)
            {
                if (is_array($value) && count($value) > 0)
                {
                    $foundkey = search_in_array($srchvalue, $value);
                    if ($foundkey != FALSE)
                        return $foundkey;
                }
            }
        }
        else
            return $foundkey;
    }
}

#15


0  

for( $i =0; $i < sizeof($allUsers); $i++)
    {   
    $NEEDLE1='firstname';
    $NEEDLE2='emailAddress';
    $sterm='Tofind';
     if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
        {
            $Fname= $allUsers[$i][$NEEDLE1];
            $Lname= $allUsers[$i][$NEEDLE2];

            $pos1 = stripos($Fname, $sterm);
            $pos2=stripos($Lname, $sterm);//not case sensitive 

            if($pos1 !== false ||$pos2 !== false)
            {$resultsMatched[] =$allUsers[$i];}
            else
            {   continue;}              
        }

}
Print_r($resultsMatched); //will give array for matched values even partially matched

With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.

在上述代码的帮助下,可以从2D数组中的任何列中找到任何(部分匹配的)数据,以便根据需要找到用户id。

#16


0  

Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

扩展@ damage创建的函数,如果您只是想匹配搜索字符串的部分(大部分),那么这个示例将更像是一个“模糊”搜索:

 function searchArrayKeyVal($sKey, $id, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
            return $key;
        }
    }
         return false;
 }

For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

例如,数组中的值欢迎访问纽约!你想要的第一个例子就是“纽约!”

#17


0  

Try this

试试这个

<?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;
 }
 ?>

#18


0  

$search1 = 'demo';
$search2 = 'bob';
$arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
foreach ($arr as $value) { 
    if (is_array($value)) { 
        if (in_array($search2, $value)) { 
            echo "successsfully";    
            //execute your code 
        }
    } else {  
        if ($value == $search1) { 
            echo "success";
        }
    }
 }

#19


0  

I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not

我想在下面的数组中检查,$arr是否在子数组中存在“abc”

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

Then i can use this

然后我可以用这个

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

I think This is the Most simple way to define

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

#20


0  

If question i.e.

如果问题即。

$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",
     ],
   ];

Ans:

答:

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));

#1


327  

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

这将工作。你应该这样称呼它:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

重要的是要知道,如果您使用的是=== =运算符比较类型,则必须完全相同,在本例中,您必须搜索字符串或仅使用==替换=== =。

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

基于angoru回答。在PHP的后续版本(>= 5.5.0)中,可以使用一行代码。

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

这是文档:http://php.net/manual/en/function.array-column.php。

#2


202  

If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.

如果您正在使用(PHP 5 >= 5.5.0),您不需要编写自己的函数来实现这一点,只需编写这一行就可以了。

If you want just one result:

如果你只想要一个结果:

$key = array_search(40489, array_column($userdb, 'uid'));

For multiple results

对多个结果

$keys = array_keys(array_column($userdb, 'uid'), 40489);

In case you have an associative array as pointed in the comments you could make it with:

如果你有一个关联数组,你可以在评论中指出:

$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);

If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!

如果您正在使用PHP < 5.5.0,您可以使用这个后台端口,谢谢ramsey!

Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!

更新:我已经做了一些简单的基准测试,多结果表单似乎是最快的,甚至比Jakub自定义函数还要快!

#3


22  

Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

基于Jakub出色的答案,这里有一个更通用的搜索,它将允许指定的键(不只是uid):

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

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

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

#4


13  

I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.

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

Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.

这是我的例子,请记住这是我的第一个答案。我取出了param数组,因为我只需要搜索一个特定的数组,但是您可以轻松地添加它。我想要搜索的不仅仅是uid。

Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.

此外,在我的情况下,可能会有多个键返回,因为其他字段可能不是惟一的。

 /**
     * @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;
    }

Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.

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

This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).

第二个示例向您展示在某个关联键(first_name)中找到一个值('Taylor'),在另一个关联键(used)中找到另一个值(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;
}

Use of function

使用的函数

$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);

Result

结果

Array ( [0] => 2 ) 

#5


8  

I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:

我在description函数array_search下面修改了一个示例。函数searchItemsByKey从多维数组(N层)返回所有值(s)。也许,这对某些人是有用的。例子:

 $arr = array(
     'XXX'=>array(
               'YYY'=> array(
                    'AAA'=> array(
                          'keyN' =>'value1'
                   )
               ),
              'ZZZ'=> array(
                    'BBB'=> array(
                          'keyN' => 'value2'
                   )
               )
              //.....
           )
);


$result = searchItemsByKey($arr,'keyN');

print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
  [0] => value1
  [1] => value2
)

Function code:

函数代码:

function searchItemsByKey($array, $key)
{
   $results = array();

  if (is_array($array))
  {
    if (isset($array[$key]) && key($array)==$key)
        $results[] = $array[$key];

    foreach ($array as $sub_array)
        $results = array_merge($results, searchItemsByKey($sub_array, $key));
  }

 return  $results;
}

#6


5  

In later versions of PHP (>= 5.5.0) you can use this one-liner:

在PHP的后续版本(>= 5.5.0)中,您可以使用以下一行:

$key = array_search('100', array_column($userdb, 'uid'));

#7


4  

Looks array_filter will be suitable solution for this...

看起来array_filter将适合这个…

$userdb=Array
(
    (0) => Array
        (
            (uid) => '100',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

PHP Code

PHP代码

<?php 
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
  return $v['uid'] => $search;
}) 

$values= print_r(array_value($found)); 
$keys =  print_r(array_keys($found)); 

#8


3  

Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.

虽然这是一个老问题,而且有一个公认的答案,但我还是建议你改变一下接受的答案。首先,我同意大家接受的答案是正确的。

function searchArrayKeyVal($sKey, $id, $array) {
   foreach ($array as $key => $val) {
       if ($val[$sKey] == $id) {
           return $key;
       }
   }
   return false;
}

Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.

用函数中的参数替换预设的“uid”,因此现在调用下面的代码意味着可以跨多个数组类型使用一个函数。很小的改变,但是有一点不同。

    // Array Data Of Users
$userdb = array (
    array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
    array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
    array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);

// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
    echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
    echo "Search Result can not be found";
}

PHP Fiddle Example

PHP小提琴的例子

#9


1  

I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:

我必须使用un函数来查找数组中的每个元素。所以我修改了函数由Jakub Truneček遵循:

function search_in_array_r($needle, $array) {
    $found = array();
    foreach ($array as $key => $val) {
        if ($val[1] == $needle) {
            array_push($found, $val[1]);
        }
    }
    if (count($found) != 0)
        return $found;
    else
        return null;
}

#10


1  

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

#11


1  

you can use this function ; https://github.com/serhatozles/ArrayAdvancedSearch

你可以用这个函数;https://github.com/serhatozles/ArrayAdvancedSearch

<?php 
include('ArraySearch.php');

$query = "a='Example World' and b>='2'";

$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);

$Result = ArraySearch($Array,$query,1);

echo '<pre>';
print_r($Result);
echo '</pre>'; 

// Output:
// Array
// (
//    [0] => Array
//        (
//            [a] => Example World
//            [b] => 2
//        )
//
// )

#12


1  

$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

$found = null;
$search = 'eee';

array_walk($a, function ($k, $v) use ($search, &$found) {
    if (in_array($search, $k)) {
        $found = $v;
    }
});

var_dump($found);

#13


1  

Here is one liner for the same,

这是一个相同的内线,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];

#14


0  

Try this also

试试这个也

function search_in_array($srchvalue, $array)
{
    if (is_array($array) && count($array) > 0)
    {
        $foundkey = array_search($srchvalue, $array);
        if ($foundkey === FALSE)
        {
            foreach ($array as $key => $value)
            {
                if (is_array($value) && count($value) > 0)
                {
                    $foundkey = search_in_array($srchvalue, $value);
                    if ($foundkey != FALSE)
                        return $foundkey;
                }
            }
        }
        else
            return $foundkey;
    }
}

#15


0  

for( $i =0; $i < sizeof($allUsers); $i++)
    {   
    $NEEDLE1='firstname';
    $NEEDLE2='emailAddress';
    $sterm='Tofind';
     if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
        {
            $Fname= $allUsers[$i][$NEEDLE1];
            $Lname= $allUsers[$i][$NEEDLE2];

            $pos1 = stripos($Fname, $sterm);
            $pos2=stripos($Lname, $sterm);//not case sensitive 

            if($pos1 !== false ||$pos2 !== false)
            {$resultsMatched[] =$allUsers[$i];}
            else
            {   continue;}              
        }

}
Print_r($resultsMatched); //will give array for matched values even partially matched

With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.

在上述代码的帮助下,可以从2D数组中的任何列中找到任何(部分匹配的)数据,以便根据需要找到用户id。

#16


0  

Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

扩展@ damage创建的函数,如果您只是想匹配搜索字符串的部分(大部分),那么这个示例将更像是一个“模糊”搜索:

 function searchArrayKeyVal($sKey, $id, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
            return $key;
        }
    }
         return false;
 }

For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

例如,数组中的值欢迎访问纽约!你想要的第一个例子就是“纽约!”

#17


0  

Try this

试试这个

<?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;
 }
 ?>

#18


0  

$search1 = 'demo';
$search2 = 'bob';
$arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
foreach ($arr as $value) { 
    if (is_array($value)) { 
        if (in_array($search2, $value)) { 
            echo "successsfully";    
            //execute your code 
        }
    } else {  
        if ($value == $search1) { 
            echo "success";
        }
    }
 }

#19


0  

I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not

我想在下面的数组中检查,$arr是否在子数组中存在“abc”

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

Then i can use this

然后我可以用这个

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

I think This is the Most simple way to define

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

#20


0  

If question i.e.

如果问题即。

$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",
     ],
   ];

Ans:

答:

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));