当前位置 : 主页 > 网络编程 > PHP >

FilterTrait.php

来源:互联网 收集:自由互联 发布时间:2021-06-28
FilterTrait.php '新键名'] * * @return array */ public function filterData( $data, $key = [ ], $newKey = [ ] ) { $info = empty( $key ) ? $data : [ ]; //过滤要显示的数据 if ( !empty( $key ) ) { foreach ( $data as $k = $v ) { $info[
FilterTrait.php
 '新键名']
     *
     * @return array
     */
    public function filterData( $data, $key = [ ], $newKey = [ ] )
    {
        $info = empty( $key ) ? $data : [ ];
        //过滤要显示的数据
        if ( !empty( $key ) ) {
            foreach ( $data as $k => $v ) {
                $info[ $k ] = $this->filterArrayKey ( $v, $key );
            }
        }

        //处理键名需要转换的
        if ( !empty( $newKey ) ) {
            foreach ( $info as $k => $v ) {
                $info[ $k ] = $this->replaceArrayKey ( $v, $newKey );
            }
        }

        return $info;
    }

    /**
     * 过滤一维数组键名
     *
     * @param       $data
     * @param array $filter
     *
     * @return mixed
     */
    public function filterArrayKey( $data, $filter )
    {
        if ( !empty( $filter ) ) {
            foreach ( $data as $key => $val ) {
                if ( !in_array ( $key, $filter ) ) {
                    unset( $data[ $key ] );
                }
            }
        }

        return $data;
    }

    /**
     * 替换键名 -> 可用于过滤和转换请求参数,用于统一处理
     *
     * @param array $data   要替换的数据
     * @param array $newKey 键值对 $newKey = [key => newKey]
     *
     * @return mixed
     */
    public function replaceArrayKey( $data, $newKey )
    {
        if ( !empty( $data ) ) {
            foreach ( $data as $nk => $nv ) {
                if ( array_key_exists ( $nk, $newKey ) ) {
                    $data[ $newKey[ $nk ] ] = $nv;
                    unset( $data[ $nk ] );
                }
            }
        }

        return $data;
    }

    /**
     * 替换键名 [可多个将遇到的多个键名转为相同的键名] -> 可用于过滤和转换请求参数,用于统一处理
     *
     * @param array $data    要替换的数据
     * @param array $keyVals 键值对
     *                       $newKey = [ newKey => [key1,key2], ...] or
     *                       $newKey = [ newKey => 'key1,key2', ...]
     *
     * @desc 键值对不允许为空
     * @return mixed
     */
    public function changeArrayKey( $data, $keyVals )
    {
        if ( !empty( $data ) ) {
            foreach ( $data as $nk => $nv ) {
                foreach ( $keyVals as $k => $v ) {
                    $v = is_string ( $v ) ? explode ( ',', $v ) : $v;
                    if ( in_array ( $nk, $v ) ) {
                        $data[ $k ] = $data[ $nk ];
                        unset( $data[ $nk ] );
                        break;
                    }
                }
            }
        }

        return $data;
    }
}
上一篇:随机数组和二维排序.php
下一篇:c.php
网友评论