假设我有一个像这样的多维数组:
array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
我如何能够计算多维数组中存在多少次“Thing1”值?
假设我有一个像这样的多维数组:
array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
我如何能够计算多维数组中存在多少次“Thing1”值?
您可以使用此http://www.php.net/manual/en/function.array-search.phparray_search
获取更多信息
此代码是 php 文档示例中的示例
<?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
} ;
?>
如果在 haystack 中多次找到 needle,则返回第一个匹配的键。要返回所有匹配值的键,请改用array_keys()
可选的 search_value 参数。
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;
}
尝试这个 :
$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
次数。
编辑:根据 OP 的评论:“你的意思是结果数组是哪个数组?” - 输入数组。因此,例如这将是输入数组: array(array(1,1),array(2,1),array(3,2)) ,我只希望它计算第一个值 (1,2,3)不是第二个值 (1,1,2) – gdscei 7 分钟前
$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'];
尝试这个
$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];
使用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
$count = 0;
foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}