假设我有一个多维数组:
[
["Thing1", "OtherThing1"],
["Thing1", "OtherThing2"],
["Thing2", "OtherThing3"]
]
我怎样才能计算出"Thing1"发生在多维数组中?
您可以使用array_search
获取更多信息,请参阅此http://www.php.net/manual/en/function.array-search.php
这段代码是PHP文档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
} ;
?>
如果在干草堆中不止一次找到针,则返回第一个匹配的键。若要返回所有匹配值的键,请使用带可选search_value参数的array_keys()
。
试试这个:
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
echo "<pre>";
$res = array_count_values(call_user_func_array('array_merge', $arr));
echo $res['Thing1'];
输出:Array
(
[Thing1] => 2
[OtherThing1] => 1
[OtherThing2] => 1
[Thing2] => 1
[OtherThing3] => 1
)
给出每个值的出现次数。即:Thing1
出现2
次。
EDIT:根据OP的评论:"您指的是哪个数组?"—输入阵列。例如,这将是输入数组:array(array(1,1),array(2,1),array(3,2)),我只希望它计算第一个值(1,2,3)而不是第二个值(1,1,2)- gdscei 7 mins ago
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$res = array_count_values(array_map(function($a){return $a[0];}, $arr));
echo $res['Thing1'];
function showCount($arr, $needle, $count=0)
{
// Check if $arr is array. Thx to Waygood
if(!is_array($arr)) return false;
foreach($arr as $k=>$v)
{
// if item is array do recursion
if(is_array($v))
{
$count = showCount($v, $needle, $count);
}
elseif($v == $needle){
$count++;
}
}
return $count;
}
使用in_array
可以帮助:
$cont = 0;
//for each array inside the multidimensional one
foreach($multidimensional as $m){
if(in_array('Thing1', $m)){
$cont++;
}
}
echo $cont;
更多信息:http://php.net/manual/en/function.in-array.php
try this
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$abc=array_count_values(call_user_func_array('array_merge', $arr));
echo $abc[Thing1];
$count = 0;
foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}
如果您希望代码简洁,零全局作用域污染,您可以计算每个值并访问您想要的一个计数:
echo array_count_values(array_merge(...$array))['Thing1'] ?? 0;
如果您不想在永远不需要计数的地方计数值,那么您可以在每次遇到目制值时使用array_walk_recursive()
和+1访问叶节点。
$thing1Count = 0;
array_walk_recursive($array, function($v) use(&$thing1Count) { $thing1Count += ($v === 'Thing1'); });
echo $thing1Count;
两个代码段都返回2
。这是一个Demo