简体   繁体   English

PHP搜索数组递归并返回索引计数?

[英]PHP Search array recursively and return count of index?

是否有一个PHP函数,允许您递归搜索数组并返回某个键'x'出现的实例数(无论有多深)?

I would use array_walk_recursive() . 我会使用array_walk_recursive() Example: 例:

$a = array(1,2,3,'x',array(4,5,'x',array(6,7,8,'x')));
$v = "x";
$i = 0;
array_walk_recursive($a, function($val, $key) use (&$i, $v) {
  if ($val == $v) {
      $i++;
  }
});
echo $i;

Output: 输出:

3

You can traverse the array recursively (that is regardless of the depth) and then count the values: 您可以递归遍历数组(无论深度如何),然后计算值:

$array  = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit    = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$xCount = 0;
foreach ($rit as $value) {
    if ($value === 'x') {
        $xCount++;
    }
}
var_dump($xCount); # int(3)

A variation of this is to convert this iteration into an array again and count values: 这种变化是将此迭代再次转换为数组并计算值:

$array  = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit    = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$allCount = array_count_values(iterator_to_array($rit, FALSE));
print_r($allCount);

Output/Result: 输出/结果:

Array
(
    [1] => 1
    [2] => 1
    [3] => 1
    [x] => 3
    [4] => 1
    [5] => 1
    [6] => 1
    [7] => 1
    [8] => 1
)

See as well: 另见:

You could write a simple recursive function that does what you want. 您可以编写一个简单的递归函数来执行您想要的操作。 I didn't test this, but the idea would be something like: 我没有测试这个,但想法是这样的:

$count = 0;
function findKey($array,&$count){
    if(!empty($array)){
        foreach($array as $key => $childArray){
            if($key == 'keyImLookingFor'){
                $count++;
            }
            findKey($childArray,$count);
        }
    }
}

$count should then contain your number of key occurrences. 然后$ count应包含您的密钥出现次数。 Again, this might need some cleanup. 同样,这可能需要一些清理。

$array = array(
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => array('key1' => 'val3'));

$count = 0;

function key_count($val, $key){
    global $count;
    if($key == "key1"){
        $count++;
    }
}

array_walk_recursive($array, 'key_count');
echo $count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM