Php 计算某个键名在多数组中出现的次数?
如何计算一个键在多数组中出现的次数 在下面的示例中,Php 计算某个键名在多数组中出现的次数?,php,arrays,multidimensional-array,count,Php,Arrays,Multidimensional Array,Count,如何计算一个键在多数组中出现的次数 在下面的示例中,weight应返回2,而reps4。PHP是否有用于此的内置函数 [0] => Array ( [0] => Array ( [weight] => 317.51474856007
weight
应返回2,而reps
4。PHP是否有用于此的内置函数
[0] => Array
(
[0] => Array
(
[weight] => 317.51474856007
[reps] => 10
)
[1] => Array
(
[weight] => 50
[reps] => 10
)
[2] => Array
(
[reps] => 10
)
[3] => Array
(
[reps] => 10
)
)
您可以尝试以下方法:
function counter($array){
$result = array();
foreach($array as $key=>$value){
foreach($value as $name => $val){
$result[$name][]=$val;
}
}
return array('all'=>$result,'count weight'=>count($result['weight']),'count reps'=>count($result['reps']));
}
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 12
),
'3' => Array
(
'reps' => 10
)
);
$resp = counter($array);
var_dump($resp);
使用以下方法尝试此单行程序:
给定阵列,$arr
array_walk_recursive($arr, function($v, $k)use(&$count){if(array_key_exists($k, $count))$count[$k]++;else $count[$k]=1;},$count=array());
print_r($count);
或者是老式的方式:
$count = array();
foreach ($arr as $ar){
foreach ($ar as $k=>$v){
if (array_key_exists($k, $count)){
$count[$k]++;
}
else{
$count[$k] = 1;
}
}
}
print_r($count);
输出:
Array
(
[weight] => 2
[reps] => 4
)
您可以尝试以下方法:
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 10
),
'3' => Array
(
'reps' => 10
)
);
$weight=0;
$reps=0;
//print_r($array);
foreach($array as $key=>$val){
if(isset($val['weight'])){
echo $val['weight']."<br>";
$weight++;
}
if(isset($val['reps'])){
echo $val['reps']."<br>";
$resp++;
}
}
echo $weight." ".$resp;
$array=array(
“0”=>数组
(
“重量”=>317.51474856007,
“重复次数”=>10次
),
“1”=>数组
(
“重量”=>50,
“重复次数”=>10次
),
“2”=>数组
(
“重复次数”=>10次
),
“3”=>数组
(
“重复次数”=>10次
)
);
$weight=0;
$reps=0;
//打印(数组);
foreach($key=>$val的数组){
如果(isset($val['weight'])){
echo$val['weight']。“
”;
$weight++;
}
如果(isset($val['reps'])){
echo$val['reps']。“
”;
$resp++;
}
}
回声$weight.“$resp;
我更喜欢函数的return$result,因为它与使用的键无关。在此基础上,我将用以下内容展开:foreach($resp as$key=>$value){echo$key.:'.count($value)。'times.;}