mysql查询返回以下结果。

id - name - class
1  - A  -    5
2  - D  -    1
3  - B  -    5
4  - c  -    1
5  - E  -    5

(由于已在id上应用了订单,因此无法进行按类别排序)

现在,我想按如下所示按类显示视图

Class 1         Class 5
id - name       id - name  
2  - D          1  - A
4  - C          3  - B
                5  - E

因此,我遵循以下步骤。

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

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


 }
} 

题:

1)如何在该循环中找到下一个键?

2)有没有更好的方法可以实现目标?

===============>>#1 票数:0

我认为这是您想要的:

//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);

  ask by Debashis translate from so

未解决问题?本站智能推荐: