我是编程php的新手,我从这样的数据库输出查询数据
name activity payment
english activ A 20
english activ B 25
english activ c 30
biology activ d 50
biology activ e 60
但我希望显示如下输出:
name activity payment
english activ A 20
activ B 25
activ c 30
biology activ d 50
activ e 60
逻辑程序如何使用PHP只显示一个同名的名字?
你可以解决这个问题吗?答案 0 :(得分:1)
数据库将显示与
相同的名称name activity payment
english activ A 20
english activ B 25
english activ c 30
biology activ d 50
biology activ e 60
但是如果你想将记录显示为
name activity payment
english activ A 20
activ B 25
activ c 30
biology activ d 50
activ e 60
你可以在php
中做到这一点例如
$datas = $fetched_data; // $fetched_data store all data which is selected from database
// now in php use foreach loop
$previous_colm = "";
foreach($datas as $data){
if($previous_colm == $data['name']){
// echo without printing column name again
echo $data['activity']." ".$data['payment'];
}else{
// echo with new column name
echo echo $data['name']." ".$data['activity']." ".$data['payment'];
}
$previous_colm = $data['name'];
}
现在这将输出你想要的...... !!!
答案 1 :(得分:0)
$arr = array(
array('name' => 'english', 'activity' => 'activ A', 'payment' => 20),
array('name' => 'english', 'activity' => 'activ B', 'payment' => 25),
array('name' => 'english', 'activity' => 'activ c', 'payment' => 30),
array('name' => 'biology', 'activity' => 'activ d', 'payment' => 50),
array('name' => 'biology', 'activity' => 'activ e', 'payment' => 60),
);
$different_names = get_different_names($arr);
echo "Name Activity Payment";
display($different_names, $arr);
function display($different_names, $arr) {
foreach($different_names as $name) {
foreach($arr as $row) {
if($row['name'] == $name)
echo "</br> {$row['name']} {$row['activity']} {$row['payment']} ";
}
}
}
function get_different_names($arr) {
$different_names = array();
foreach($arr as $row) {
if(!in_array($row['name'], $different_names))
$different_names[] = $row['name'];
}
return $different_names;
}
P.S。 Zebi Rajpot的解决方案很好。但是如果结果没有按 name 排序,我认为它不会产生所需的输出。