计算多维数组中的出现次数

时间:2018-02-08 00:01:23

标签: php

我试图找出一种计算多维数组中出现次数的方法。该数组如下所示:

$arr = [
  "apple",
  ["banana", "strawberry", "apple"],
  ["banana", "strawberry", "apple", ["banana", "strawberry", "apple"]]
];

我得到的代码是:

$count = 0;
    foreach ($arr as $arritem) {
      if ($arritem === "apple") {
        $count++;
      }
 }
 echo $count;

当我搜索“Apple”时,我得到q的输出。不知道我在这里做错了什么。我需要输出为4.任何帮助?

感谢。

3 个答案:

答案 0 :(得分:6)

这是因为您的数组$arr包含一个字符串(apple)和数组:

$arr = [
  "apple",
  ["banana", "strawberry", "apple"],
  ["banana", "strawberry", "apple", ["banana", "strawberry", "apple"]]
];

$count = 0;

foreach ($arr as $arritem) {
    // first iteration: $arritem is "apple"
    // second iteration: $arritem is ["banana", ...]
    // third iteration: $arritem is ["banana", ...]
    if ($arritem === "apple") {
        $count++;
    }
}

echo $count;

$arritem === "apple"仅适用于数组中的一个元素,因此输出1

如何解决?使用array_walk_recursive递归遍历数组:

$count = 0;

array_walk_recursive($arr, function($item) use (&$count) {
    if ($item === "apple") ++$count;
});

echo $count; // outputs 4

答案 1 :(得分:2)

在这种情况下,您正在查看数组的迭代,在您的情况下是错误的。

结果是一个,因为$arr[0]apple,但例如$arr[1]是一个数组

你需要知道你要找的是一个数组,你可以使用php的is_array

这应该有用; 用范围内的计数编辑

$arr = [ "apple", ["banana", "strawberry", "apple"],["banana", "strawberry", "apple", ["banana", "strawberry", "apple"]] ];


function loopArray($array)
{
    $count = 0;
    foreach ($array as $item){

        if(is_array($item) ){

           $count +=  loopArray($item);
        }else{
            if ($item === "apple") {
                $count++;
            }
        } 
    }
    return $count;
}


echo loopArray($arr);

答案 2 :(得分:0)

递归是你的朋友。 Foreach循环在这里不能有效地工作,因为它们不会遍历嵌套数组。

您希望迭代每个索引并检查增量或递归到另一个数组。

此处还有一个包含以下代码的涂鸦:

https://www.tehplayground.com/DOQ0qzBpY2blUBUn

<?php

$arr = [
    "apple",
    [
        "banana", 
        "strawberry", 
        "apple"
    ],
    [
        "banana", 
        "strawberry", 
        "apple", 
        [
            "banana", 
            "strawberry", 
            "apple"
        ]
    ]
];

/**
 * Return number of times we find $key in arrays
 * 
 * @param  {array}   $arr    The array to recurse through
 * @param  {string}  $key    Name of key to search for
 * @param  {int}     $found  Number of times we've found the key in the arrays
 * @return {int}
 */

function recurse_arrays($arr, $key, $found = 0) {
    foreach ($arr as $index) {
        if (is_array($index)) {
            $found = recurse_arrays($index, $key, $found);
        } else if ($index == $key) {
            $found++;
        }
    }

    return $found;
}

$timesAppeared = recurse_arrays($arr, 'apple');

echo "'apple' appeared $timesAppeared times";

// 'apple' appeared 4 times