如何计算不同表格单元格中的所有名称以获得这样的结果?
- 鲍勃-7
- 亚历-3
- 伊凡-5
- 尼娜-5-
.........
使用此代码:
<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr[]= $k1;
$total_values = array_count_values($arr);
}
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
我的输出结果是:
- 鲍勃-3
- 亚历-1
- 伊凡-1
- 尼娜-2
当我将代码更改为:
时<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr=array($k1, $k2);
$total_values = array_count_values($arr);
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
}
我的输出结果是:
- 鲍勃-1
- 亚历-1
- 伊凡-1
- 尼娜-1
- 尼娜-1
- 鲍勃-1
- 鲍勃-1
- 伊凡-1
- 尼娜-1
- 尼娜-1
.......
在数组$ arr中添加$ k2,$ k3 .... $ k6有什么问题?我需要做什么?
答案 0 :(得分:3)
这将计算单个名称的出现次数:
$q= mysqli_query($db, 'SELECT * FROM names');
$arr = array();
// 1) loop through rows
while ($all = mysqli_fetch_array($q, MYSQLI_NUM)) {
// 2) loop through cells in a row
foreach($all as $val) {
// 3) 'roll out' the values into a one-dimensional array
if(empty($val)) { continue; } // if you don't want to count empty cells
$arr[] = $val;
}
}
// 4) count the number of occurences
$names_qty = array_count_values($arr);
// optional loop that shows the results
foreach($names_qty as $name=>$qty) {
echo $name.'-'.$qty.'<br />';
}
此解决方案的好处是您只能调用一次计数函数而不是每次迭代。
答案 1 :(得分:-1)
您必须在循环中累积数据并在处理完所有数据后将其打印出来。
$total = array();
$result = mysqli_query($db, 'SELECT * FROM names', MYSQLI_USE_RESULT);
while (mysqli_fetch_assoc($result) as $row) {
foreach ($row as $col => $value)
total[$col]++;
}
}
print_r($total);
答案 2 :(得分:-1)
此代码已经过测试,应该可以解决问题。
<?php
$arr = array();
$q = mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_assoc($q)) {
foreach($all as $val) {
if(empty($val)) {
continue;
}
// saves all names with the name as key
$arr[$val][] = $val;
}
}
// Output
foreach($arr as $k => $v) {
// count how many times the name was pushed into the array
echo $k.' - '. count($v);
}