计算多维数组中的某些值

时间:2013-03-25 10:30:45

标签: php multidimensional-array

假设我有一个像这样的多维数组:

array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);

我如何计算多维数组中“Thing1”值的存在次数?

6 个答案:

答案 0 :(得分:3)

您可以使用array_search了解更多信息,请参阅此http://www.php.net/manual/en/function.array-search.php

此代码是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,则会返回第一个匹配的键。要返回所有匹配值的键,请使用带有可选search_value参数的array_keys()

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

答案 1 :(得分:2)

试试这个:

$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'];

答案 2 :(得分:2)

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;  
}

答案 3 :(得分:1)

使用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

答案 4 :(得分:1)

试试这个

$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];

答案 5 :(得分:0)

$count = 0;

foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}