douren6035 2016-04-14 10:47
浏览 29
已采纳

php根据第2表排序数据

I have two tables: Table 1 and Table 2

enter image description here

I need to sort the data as shown in Table View.

I have already taken:

foreach($Table1 as $row1 )
{
    foreach($Table2 as $row2 )
    {
          if($row1->id == $row2->selected_id)
          {
                  show??
          }
    }

}

please do not worry about queries: it is taken care of real issue is:

there is only one problem: Table 1 is generated from 20 different function and collects to Table 1. and user selects which they want to view by selecting. so, if there is total of 7 rows and user selects 3, so data will be sorted showing 3 rows selected at first rows and rest after the 3 rows.

is this the right way to do it? or is there much easier way I am using MySQL

please help anyone?

  • 写回答

6条回答 默认 最新

  • duandeng2011 2016-04-14 12:09
    关注

    As per your additional question, it seems that you don't want to use MySQL for that, and that your user selection is in fact an array like this one:

    $filter = [ 3, 4, 7, 8 ];
    

    Filter the original $Table1 array by using array_reduce. With this method you obtain an array ($filtered) with user selection in element 0 and other values in element 1:

    $filtered = array_reduce
    (
        $Table1,
        function( $carry, $item ) use( $filter )
        {
            $index = !in_array( $item['id'], $filter );
            $carry[$index][] = $item;
            return $carry;
        },
        [ [], [] ]
    );
    

    Then, merge $filtered data with call_user_func_array:

    $result = call_user_func_array( 'array_merge', $filtered );
    

    Result:

    Array
    (
        [0] => Array
            (
                [id] => 3
                [name] => C
            )
        [1] => Array
            (
                [id] => 4
                [name] => D
            )
        [2] => Array
            (
                [id] => 7
                [name] => G
            )
        [3] => Array
            (
                [id] => 8
                [name] => H
            )
        [4] => Array
            (
                [id] => 1
                [name] => A
            )
        [5] => Array
            (
                [id] => 2
                [name] => B
            )
        [6] => Array
            (
                [id] => 5
                [name] => E
            )
        [7] => Array
            (
                [id] => 6
                [name] => F
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂