Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of a specific value in multidimensional array

Let's say I have a multidimensional array like this:

[
    ["Thing1", "OtherThing1"],
    ["Thing1", "OtherThing2"],
    ["Thing2", "OtherThing3"]
]

How would I be able to count how many times the value "Thing1" occurs in the multidimensional array?

like image 942
Deniz Zoeteman Avatar asked Jan 24 '26 21:01

Deniz Zoeteman


1 Answers

you can use array_search for more information see this http://www.php.net/manual/en/function.array-search.php

this code is sample of this that is in php document sample

<?php 
function recursiveArraySearchAll($haystack, $needle, $index = null) 
{ 
 $aIt     = new RecursiveArrayIterator($haystack); 
 $it    = new RecursiveIteratorIterator($aIt); 
 $resultkeys; 

 while($it->valid()) {        
 if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle 
 $resultkeys[]=$aIt->key(); //return $aIt->key(); 
 } 

 $it->next(); 
 } 
 return $resultkeys;  // return all finding in an array 

} ; 
?> 

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

http://www.php.net/manual/en/function.array-keys.php

like image 63
mohammad mohsenipur Avatar answered Jan 27 '26 10:01

mohammad mohsenipur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!