Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

php - Counts occurrences in multidimensional array

I am trying to find out a way of counting number of occurrences in a multidimensional array. The array looks like this:

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

The code that i have got is this:

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

I get the output of q when I search for "Apple". Not sure what am I doing wrong here. I need the output to be 4. Any help?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This happens because your array $arr contains a string (apple) and arrays:

$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" only holds true for one element in the array, hence the output 1.

How to fix ? Use array_walk_recursive to recursively walk the array(s):

$count = 0;

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

echo $count; // outputs 4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...