douwo6738 2019-05-02 22:10
浏览 120
已采纳

使用eval()按wordpress的多个条件对多个数组进行排序

I'm getting a multi-dimensional array from a mysql query. Acually I'm using the following function which is working. But I use the php eval() function inside.

SORTER:

function array_sorter() {

    $sortstring = '';
    $sortarray  = func_get_arg( 0 );
    $count      = ( func_num_args() - 1 ) / 2;

    foreach ( $sortarray as $key => $row ) :

        for ( $i = 1; $i <= $count; $i++ ) {

            $str ="\$key" . $i . " = \"" . func_get_arg( $i * 2 - 1 ) . "\";";
            $str = $str . "\$array" . $i . "[\$key] = \$row[\$key" . $i . "];";
            $str = $str . "\$\$key" . $i . " = \$array" . $i . ";";
            @eval( $str );

        }

    endforeach;

    for ( $i = 1; $i <= $count; $i++ ) {
        $key1          = func_get_arg( $i * 2 - 1 );
        $sortstring = $sortstring . "\$" . $key1 . ", " . func_get_arg( $i * 2 ) . ", ";
    }

    $sortstring = "array_multisort( " . $sortstring . "\$sortarray );";
    eval( $sortstring );

    return $sortarray;

}

USAGE:

$this->tabelle = array_sorter( $table, 'Rank', 0 );

ARRAY:

Array
(
    [Club] => Club 1
    [Number] => 4
    [Win] => 4
    [Draw] => 0
    [Lost] => 0
    [Pos_Points] => 8
    [Neg_Points] => 0
    [Pos_Goals] => 244
    [Neg_Goals] => 194
    [Diff_Points] => 8
    [Diff_Goals] => 50
    [Rank] => 1
)

Array
(
    [Club] => Club 2
    [Number] => 3
    [Win] => 2
    [Draw] => 1
    [Lost] => 0
    [Pos_Points] => 5
    [Neg_Points] => 1
    [Pos_Goals] => 173
    [Neg_Goals] => 163
    [Diff_Points] => 4
    [Diff_Goals] => 10
    [Rank] => 2
)

It's I said the function is working well but I don't know about the security by using the eval() function.

Is there a way to to get it working without using the eval() to minify the security risk and using best practise php coding standards (PHP 7).

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongque4778 2019-05-20 20:40
    关注

    I found a great solution on php.net thats works for me.

    function array_orderby() {
    
        $args = func_get_args();
        $data = array_shift( $args );
    
        foreach ( $args as $n => $field ) :
    
            if ( is_string( $field ) ) {
    
                $tmp = array();
    
                foreach ( $data as $key => $row ) {
                    $tmp[ $key ] = $row[ $field ];
                }
    
                $args[ $n ] = $tmp;
    
            }
    
        endforeach;
    
        $args[] = &$data;
        call_user_func_array( 'array_multisort', $args );
    
        return array_pop( $args );
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题
  • ¥15 有没有代做有偿主要做数据可视化部分即可(2023全国高考更省一本线理科类)