[英]How to sort a result and display group wise
The mysql query is returning the below result. mysql查询返回以下结果。
id - name - class
1 - A - 5
2 - D - 1
3 - B - 5
4 - c - 1
5 - E - 5
(class wise ordering is not possible as order has been applied on id) (由于已在id上应用了订单,因此无法进行按类别排序)
Now, i want to display the view according to class wise like below 现在,我想按如下所示按类显示视图
Class 1 Class 5
id - name id - name
2 - D 1 - A
4 - C 3 - B
5 - E
So, i followed the below steps. 因此,我遵循以下步骤。
1) Created two separate arrays using array_push() 1)使用array_push()创建两个单独的数组
array_push($class_array, $class); // indicates the class
array_push($other_array, $other); // $other indicates the string 'id - name';
2) asort($class_array); 2)asort($ class_array);
3) Executing the below foreach loop and i am stuck on this 3)执行下面的foreach循环,我被困在这个
$new_c_array = array();
$table_array = array();
foreach ($class_array as $key => $val) {
if (in_array($key, $new_c_array)) {
$view_val = $other_array[$key];
//**I am stuck in this section**
// trying to find the next key from $class_array and check whether it is same of current key
// if same then, its fine
// else $view_val .= '</table>'
array_push($table_array, $view_val);
} else {
array_push($new_c_array, $val);
$view_val = '<table>';
$view_val .= '<tr>';
$view_val .= '<td> Class' . $val . '</td>';
$view_val .= '</tr>';
$view_val .= $other_array[$key];
array_push($table_array, $view_val);
}
}
Question: 题:
1) How can i find the next key within that loop? 1)如何在该循环中找到下一个键?
2) Is there any better way to accomplish the goal? 2)有没有更好的方法可以实现目标?
I think this is what you want: 我认为这是您想要的:
//you array from DB
$dataArray=array(
1 => array(
'name' => A,
'class' => 5
),
2 => array(
'name' => D,
'class' => 1
),
3 => array(
'name' => B,
'class' => 5
),
4 => array(
'name' => C,
'class' => 1
),
5 => array(
'name' => E,
'class' => 5
)
);
$resultArray=array();
foreach($dataArray as $key=>$value){
$resultArray[$value['class']][]=array(
'name' => $value['name'],
'id' => $key
);
}
print_r($resultArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.