如何在PHP多维数组中按key=>值进行搜索

时间:2021-09-30 22:08:19

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.

在多维数组中找到键值对的所有子数组,有没有快速的方法?我不能说数组有多深。

Simple example array:

简单的例子数组:

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1")
);

When I search for key=name and value="cat 1" the function should return:

当我搜索key=name和value="cat 1"时,函数应该返回:

array(0 => array(id=>1,name=>"cat 1"),
      1 => array(id=>3,name=>"cat 1")
);

I guess the function has to be recursive to get down to the deepest level.

我猜这个函数必须是递归的才能达到最深的层次。

14 个解决方案

#1


188  

Code:

代码:

function search($array, $key, $value)
{
    $results = array();

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

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

如果效率很重要,您可以编写它,以便所有递归调用将结果存储在相同的临时$results数组中,而不是合并数组,如下所示:

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

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

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

这里的关键是search_r通过引用而不是值来获取它的第四个参数;&符号是关键。

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

提示:如果您有一个较老的PHP版本,那么您必须在对search_r的调用中指定引用传递部分,而不是在声明中指定引用传递部分。也就是说,最后一行变成search_r($subarray, $key, $value, &$results)。

#2


68  

How about the SPL version instead? It'll save you some typing:

那么SPL版本呢?它会帮你省去一些打字:

// I changed your input example to make it harder and
// to show it works at lower depths:

$arr = array(0 => array('id'=>1,'name'=>"cat 1"),
             1 => array(array('id'=>3,'name'=>"cat 1")),
             2 => array('id'=>2,'name'=>"cat 2")
);

//here's the code:

    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

 foreach ($arrIt as $sub) {
    $subArray = $arrIt->getSubIterator();
    if ($subArray['name'] === 'cat 1') {
        $outputArray[] = iterator_to_array($subArray);
    }
}

What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

最重要的是,基本上相同的代码会通过使用一个递归的directoryiterator而不是一个递归的迭代器来遍历一个目录。SPL roxor。

The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

关于SPL唯一的问题是它在网络上的记录很糟糕。但是有几本PHP书籍介绍了一些有用的细节,特别是专业PHP;你也可以通过谷歌获得更多的信息。

#3


35  

<?php
$arr = array(0 => array("id"=>1,"name"=>"cat 1"),
             1 => array("id"=>2,"name"=>"cat 2"),
             2 => array("id"=>3,"name"=>"cat 1")
);
$arr = array_filter($arr, function($ar) {
   return ($ar['name'] == 'cat 1');
   //return ($ar['name'] == 'cat 1' AND $ar['id'] == '3');// you can add multiple conditions
});

echo "<pre>";
print_r($arr);

?>

Ref: http://php.net/manual/en/function.array-filter.php

裁判:http://php.net/manual/en/function.array-filter.php

#4


16  

Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman's great answer up above.

我回来了,为任何需要对这些答案进行优化的人,尤其是约翰·库格曼的伟大的回答,发布了这个更新。

His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

他的post函数可以正常工作,但我必须对这个场景进行优化,以处理12000行结果集。这个函数需要8秒才能完成所有记录,太长了。

I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

我只需要函数在找到匹配时停止搜索和返回。如果搜索customer_id,我们知道只有一个在resultset中,一旦在多维数组中找到customer_id,我们就想返回。

Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

这里是这个函数的速度优化(并且简化了很多)版本,适合任何需要帮助的人。与其他版本不同的是,它只能处理一个深度的数组,不会递归,并且不会合并多个结果。

// search array for specific key = value
public function searchSubArray(Array $array, $key, $value) {   
    foreach ($array as $subarray){  
        if (isset($subarray[$key]) && $subarray[$key] == $value)
          return $subarray;       
    } 
}

This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costly but much more reasonable.

这就降低了这项任务,将12000条记录匹配到1.5秒。仍然非常昂贵,但是更加合理。

#5


14  

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

对快速版本的一个小改进。

#6


7  

Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:

在多维数组中,要注意线性搜索算法(上面是线性的),因为它们的复杂性增加了复杂性,因为它的深度增加了遍历整个数组所需的迭代次数。例如:

array(
    [0] => array ([0] => something, [1] => something_else))
    ...
    [100] => array ([0] => something100, [1] => something_else100))
)

would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.

要找到你要找的东西(如果针在[100][1]),就需要使用最多达200次的迭代,并使用合适的算法。

Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:

在这种情况下,线性算法在O(n)(整个数组中元素的顺序总数)上执行,这是很糟糕的,100万个条目(例如1000x100x10数组)平均需要50万次迭代才能找到针头。如果你决定改变多维数组的结构会发生什么?如果深度大于100,PHP就会推出递归算法。计算机科学可以做得更好:

Where possible, always use objects instead of multiple dimensional arrays:

在可能的情况下,总是使用对象而不是多维数组:

ArrayObject(
   MyObject(something, something_else))
   ...
   MyObject(something100, something_else100))
)

and apply a custom comparator interface and function to sort and find them:

并应用自定义比较器接口和函数对其进行排序和查找:

interface Comparable {
   public function compareTo(Comparable $o);
}

class MyObject implements Comparable {
   public function compareTo(Comparable $o){
      ...
   }
}

function myComp(Comparable $a, Comparable $b){
    return $a->compareTo($b);
}

You can use uasort() to utilize a custom comparator, if you're feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).

您可以使用uasort()来使用自定义比较器,如果您喜欢冒险,您应该为您的对象实现自己的集合,以便对它们进行排序和管理(我总是将ArrayObject扩展到至少包含一个搜索函数)。

$arrayObj->uasort("myComp");

Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes ~20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP (array_search() uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.

一旦它们被排序(uasort是O(n log n),这和它处理任意数据一样好),二分搜索可以在O(log n)时间内完成操作,也就是100万个条目只需要20次迭代。就我所知,自定义比较器二进制搜索不是在PHP中实现的(array_search()使用的是对对象引用而不是它们的属性起作用的自然排序),您必须像我一样自己实现它。

This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)

这种方法更有效(不再有深度),更重要的是更通用(假设您使用接口强制可比性),因为对象定义了它们的排序方式,因此您可以无限地循环代码。更好的=)

#7


5  

$result = array_filter($arr, function ($var) {   
  $found = false;
  array_walk_recursive($var, function ($item, $key) use (&$found) {  
    $found = $found || $key == "name" && $item == "cat 1";
  });
  return $found;
});

#8


3  

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

<?php

//PHP 5.3

function searchNestedArray(array $array, $search, $mode = 'value') {

    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}})
            return true;
    }
    return false;
}

$data = array(
    array('abc', 'ddd'),
    'ccc',
    'bbb',
    array('aaa', array('yyy', 'mp' => 555))
);

var_dump(searchNestedArray($data, 555));

#9


3  

function in_multi_array($needle, $key, $haystack) 
{
    $in_multi_array = false;
    if (in_array($needle, $haystack))
    {
        $in_multi_array = true; 
    }else 
    {
       foreach( $haystack as $key1 => $val )
       {
           if(is_array($val)) 
           {
               if($this->in_multi_array($needle, $key, $val)) 
               {
                   $in_multi_array = true;
                   break;
               }
           }
        }
    }

    return $in_multi_array;
} 

#10


2  

I needed something similar, but to search for multidimensional array by value... I took John example and wrote

我需要类似的东西,但要通过值搜索多维数组…我以约翰为例写作

function _search_array_by_value($array, $value) {
        $results = array();
        if (is_array($array)) {
            $found = array_search($value,$array);
            if ($found) {
                $results[] = $found;
            }
            foreach ($array as $subarray)
                $results = array_merge($results, $this->_search_array_by_value($subarray, $value));
        }
        return $results;
    }

I hope it helps somebody :)

我希望它能帮助一些人:)

#11


2  

This is a revised function from the one that John K. posted... I need to grab only the specific key in the array and nothing above it.

这是一个修改后的函数,来自John k。我只需要获取数组中的特定键,而不需要其他键。

function search_array ( $array, $key, $value )
{
    $results = array();

    if ( is_array($array) )
    {
        if ( $array[$key] == $value )
        {
            $results[] = $array;
        } else {
            foreach ($array as $subarray) 
                $results = array_merge( $results, $this->search_array($subarray, $key, $value) );
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
       1 => array(id=>2,name=>"cat 2"),
       2 => array(id=>3,name=>"cat 1"));

print_r(search_array($arr, 'name', 'cat 1'));

#12


2  

Here is solution:

这是解决方案:

<?php
$students['e1003']['birthplace'] = ("Mandaluyong <br>");
$students['ter1003']['birthplace'] = ("San Juan <br>");
$students['fgg1003']['birthplace'] = ("Quezon City <br>");
$students['bdf1003']['birthplace'] = ("Manila <br>");

$key = array_search('Delata Jona', array_column($students, 'name'));
echo $key;  

?>

#13


1  

And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):

另一个版本从数组元素中返回键值(没有递归,为速度优化):

// if the array is 
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);

//then 
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) ) 
// instead of Array ( [0] => Array ( [id] => 2 ) )

// search array for specific key = value
function search_array($array, $key, $value) {
  $return = array();   
  foreach ($array as $k=>$subarray){  
    if (isset($subarray[$key]) && $subarray[$key] == $value) {
      $return[$k] = $subarray;
      return $return;
    } 
  }
}

Thanks to all who posted here.

感谢所有在这里发帖的人。

#14


1  

function findKey($tab, $key){
    foreach($tab as $k => $value){ 
        if($k==$key) return $value; 
        if(is_array($value)){ 
            $find = findKey($value, $key);
            if($find) return $find;
        }
    }
    return null;
}

#1


188  

Code:

代码:

function search($array, $key, $value)
{
    $results = array();

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

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

如果效率很重要,您可以编写它,以便所有递归调用将结果存储在相同的临时$results数组中,而不是合并数组,如下所示:

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

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

    foreach ($array as $subarray) {
        search_r($subarray, $key, $value, $results);
    }
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

这里的关键是search_r通过引用而不是值来获取它的第四个参数;&符号是关键。

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

提示:如果您有一个较老的PHP版本,那么您必须在对search_r的调用中指定引用传递部分,而不是在声明中指定引用传递部分。也就是说,最后一行变成search_r($subarray, $key, $value, &$results)。

#2


68  

How about the SPL version instead? It'll save you some typing:

那么SPL版本呢?它会帮你省去一些打字:

// I changed your input example to make it harder and
// to show it works at lower depths:

$arr = array(0 => array('id'=>1,'name'=>"cat 1"),
             1 => array(array('id'=>3,'name'=>"cat 1")),
             2 => array('id'=>2,'name'=>"cat 2")
);

//here's the code:

    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

 foreach ($arrIt as $sub) {
    $subArray = $arrIt->getSubIterator();
    if ($subArray['name'] === 'cat 1') {
        $outputArray[] = iterator_to_array($subArray);
    }
}

What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

最重要的是,基本上相同的代码会通过使用一个递归的directoryiterator而不是一个递归的迭代器来遍历一个目录。SPL roxor。

The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

关于SPL唯一的问题是它在网络上的记录很糟糕。但是有几本PHP书籍介绍了一些有用的细节,特别是专业PHP;你也可以通过谷歌获得更多的信息。

#3


35  

<?php
$arr = array(0 => array("id"=>1,"name"=>"cat 1"),
             1 => array("id"=>2,"name"=>"cat 2"),
             2 => array("id"=>3,"name"=>"cat 1")
);
$arr = array_filter($arr, function($ar) {
   return ($ar['name'] == 'cat 1');
   //return ($ar['name'] == 'cat 1' AND $ar['id'] == '3');// you can add multiple conditions
});

echo "<pre>";
print_r($arr);

?>

Ref: http://php.net/manual/en/function.array-filter.php

裁判:http://php.net/manual/en/function.array-filter.php

#4


16  

Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman's great answer up above.

我回来了,为任何需要对这些答案进行优化的人,尤其是约翰·库格曼的伟大的回答,发布了这个更新。

His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

他的post函数可以正常工作,但我必须对这个场景进行优化,以处理12000行结果集。这个函数需要8秒才能完成所有记录,太长了。

I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

我只需要函数在找到匹配时停止搜索和返回。如果搜索customer_id,我们知道只有一个在resultset中,一旦在多维数组中找到customer_id,我们就想返回。

Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

这里是这个函数的速度优化(并且简化了很多)版本,适合任何需要帮助的人。与其他版本不同的是,它只能处理一个深度的数组,不会递归,并且不会合并多个结果。

// search array for specific key = value
public function searchSubArray(Array $array, $key, $value) {   
    foreach ($array as $subarray){  
        if (isset($subarray[$key]) && $subarray[$key] == $value)
          return $subarray;       
    } 
}

This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costly but much more reasonable.

这就降低了这项任务,将12000条记录匹配到1.5秒。仍然非常昂贵,但是更加合理。

#5


14  

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

对快速版本的一个小改进。

#6


7  

Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:

在多维数组中,要注意线性搜索算法(上面是线性的),因为它们的复杂性增加了复杂性,因为它的深度增加了遍历整个数组所需的迭代次数。例如:

array(
    [0] => array ([0] => something, [1] => something_else))
    ...
    [100] => array ([0] => something100, [1] => something_else100))
)

would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.

要找到你要找的东西(如果针在[100][1]),就需要使用最多达200次的迭代,并使用合适的算法。

Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:

在这种情况下,线性算法在O(n)(整个数组中元素的顺序总数)上执行,这是很糟糕的,100万个条目(例如1000x100x10数组)平均需要50万次迭代才能找到针头。如果你决定改变多维数组的结构会发生什么?如果深度大于100,PHP就会推出递归算法。计算机科学可以做得更好:

Where possible, always use objects instead of multiple dimensional arrays:

在可能的情况下,总是使用对象而不是多维数组:

ArrayObject(
   MyObject(something, something_else))
   ...
   MyObject(something100, something_else100))
)

and apply a custom comparator interface and function to sort and find them:

并应用自定义比较器接口和函数对其进行排序和查找:

interface Comparable {
   public function compareTo(Comparable $o);
}

class MyObject implements Comparable {
   public function compareTo(Comparable $o){
      ...
   }
}

function myComp(Comparable $a, Comparable $b){
    return $a->compareTo($b);
}

You can use uasort() to utilize a custom comparator, if you're feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).

您可以使用uasort()来使用自定义比较器,如果您喜欢冒险,您应该为您的对象实现自己的集合,以便对它们进行排序和管理(我总是将ArrayObject扩展到至少包含一个搜索函数)。

$arrayObj->uasort("myComp");

Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes ~20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP (array_search() uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.

一旦它们被排序(uasort是O(n log n),这和它处理任意数据一样好),二分搜索可以在O(log n)时间内完成操作,也就是100万个条目只需要20次迭代。就我所知,自定义比较器二进制搜索不是在PHP中实现的(array_search()使用的是对对象引用而不是它们的属性起作用的自然排序),您必须像我一样自己实现它。

This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)

这种方法更有效(不再有深度),更重要的是更通用(假设您使用接口强制可比性),因为对象定义了它们的排序方式,因此您可以无限地循环代码。更好的=)

#7


5  

$result = array_filter($arr, function ($var) {   
  $found = false;
  array_walk_recursive($var, function ($item, $key) use (&$found) {  
    $found = $found || $key == "name" && $item == "cat 1";
  });
  return $found;
});

#8


3  

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

<?php

//PHP 5.3

function searchNestedArray(array $array, $search, $mode = 'value') {

    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}})
            return true;
    }
    return false;
}

$data = array(
    array('abc', 'ddd'),
    'ccc',
    'bbb',
    array('aaa', array('yyy', 'mp' => 555))
);

var_dump(searchNestedArray($data, 555));

#9


3  

function in_multi_array($needle, $key, $haystack) 
{
    $in_multi_array = false;
    if (in_array($needle, $haystack))
    {
        $in_multi_array = true; 
    }else 
    {
       foreach( $haystack as $key1 => $val )
       {
           if(is_array($val)) 
           {
               if($this->in_multi_array($needle, $key, $val)) 
               {
                   $in_multi_array = true;
                   break;
               }
           }
        }
    }

    return $in_multi_array;
} 

#10


2  

I needed something similar, but to search for multidimensional array by value... I took John example and wrote

我需要类似的东西,但要通过值搜索多维数组…我以约翰为例写作

function _search_array_by_value($array, $value) {
        $results = array();
        if (is_array($array)) {
            $found = array_search($value,$array);
            if ($found) {
                $results[] = $found;
            }
            foreach ($array as $subarray)
                $results = array_merge($results, $this->_search_array_by_value($subarray, $value));
        }
        return $results;
    }

I hope it helps somebody :)

我希望它能帮助一些人:)

#11


2  

This is a revised function from the one that John K. posted... I need to grab only the specific key in the array and nothing above it.

这是一个修改后的函数,来自John k。我只需要获取数组中的特定键,而不需要其他键。

function search_array ( $array, $key, $value )
{
    $results = array();

    if ( is_array($array) )
    {
        if ( $array[$key] == $value )
        {
            $results[] = $array;
        } else {
            foreach ($array as $subarray) 
                $results = array_merge( $results, $this->search_array($subarray, $key, $value) );
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
       1 => array(id=>2,name=>"cat 2"),
       2 => array(id=>3,name=>"cat 1"));

print_r(search_array($arr, 'name', 'cat 1'));

#12


2  

Here is solution:

这是解决方案:

<?php
$students['e1003']['birthplace'] = ("Mandaluyong <br>");
$students['ter1003']['birthplace'] = ("San Juan <br>");
$students['fgg1003']['birthplace'] = ("Quezon City <br>");
$students['bdf1003']['birthplace'] = ("Manila <br>");

$key = array_search('Delata Jona', array_column($students, 'name'));
echo $key;  

?>

#13


1  

And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):

另一个版本从数组元素中返回键值(没有递归,为速度优化):

// if the array is 
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);

//then 
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) ) 
// instead of Array ( [0] => Array ( [id] => 2 ) )

// search array for specific key = value
function search_array($array, $key, $value) {
  $return = array();   
  foreach ($array as $k=>$subarray){  
    if (isset($subarray[$key]) && $subarray[$key] == $value) {
      $return[$k] = $subarray;
      return $return;
    } 
  }
}

Thanks to all who posted here.

感谢所有在这里发帖的人。

#14


1  

function findKey($tab, $key){
    foreach($tab as $k => $value){ 
        if($k==$key) return $value; 
        if(is_array($value)){ 
            $find = findKey($value, $key);
            if($find) return $find;
        }
    }
    return null;
}