数组 只保留 给定键

$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;
    }
}

此处评论已关闭