数组 只保留 给定键
$visible = [
    'a',
    'b',
    'c' => [
        'a' => [
            'b',
        ],
        'd',
    ],
    'd',
];
$arr = [
    'a' => 0,
    'b' => 1,
    'c' => [
        'a' => [
            'a' => 2,
            'b' => 3,
        ],
        'b' => 4,
        'd' => 5,
    ],
    'd' => 6,
];
trait FilterTrait
{
    public function filterOutputData($visible, $data)
    {
        $res = [];
        foreach ($visible as $key => $value) {
            // 输出字段
            if (is_string($value)) {
                if (array_key_exists($value, $data)) {
                    $res[$value] = $data[$value];
                }
            }
            // 输出字段在数组里
            if (is_array($value)) {
                if (array_key_exists($key, $data)) {
                    $res[$key] = is_null($data[$key]) ? null : $this->filterOutputData($value, $data[$key]);
                }
            }
        }
        return $res;
    }
    /**
     * 过滤输出的列表
     *
     * [
     *   // 普通的key
     *   'key1',
     *   // 当前key对应一个数组时候
     *   'key2' => [
     *       'key1' => [
     *           'val',
     *       ],
     *       'key2',
     *   ],
     * ];
     */
    public function filterOutputList($visible, $list)
    {
        $res = [];
        foreach ($list as $key => $value) {
            $res[$key] = $this->filterOutputData($visible, $value);
        }
        return $res;
    }
}					最后更新于 2021-03-05 09:02:48 并被添加「」标签,已有 1499 位童鞋阅读过。
此处评论已关闭