Php 选择要在数组数组中显示的字段

Php 选择要在数组数组中显示的字段,php,arrays,Php,Arrays,我有这样一个数据数组: dataArray = [ 'index1' => 'value1', 'index2' => 'value2', 'index3' => '[ 'index1' => 'value1', 'index2' => [ 'index1' => 'value1', ], 'index3' => 'value3', ] ] 数组的维度未知 我有另一个数组,它定义了需要

我有这样一个数据数组:

dataArray = [ 
  'index1' => 'value1',
  'index2' => 'value2',
  'index3' => '[
    'index1' => 'value1',
    'index2' => [ 
       'index1' => 'value1',
     ],
    'index3' => 'value3',
  ]
]
数组的维度未知

我有另一个数组,它定义了需要打印的dataArray中的值:

maskArray = ['index2', 'index3' => [ 'index1', 'index2' => [ 'index1' ] ]]
我需要输出一个与maskArray和dataArray中的字段匹配的数组,因此在这种情况下,输出应该是:

result = [ 
  'index2' => 'value2',
  'index3' => [
    'index1' => 'value1' 
    'index2' => [
      'index1' => 'value1'
    ]
  ]
]

在这种情况下,maskArray有3层深,但可能有n层深。

如果您不知道数组的嵌套深度,递归解决方案可能是合适的。也许有更好的,但我认为这是非常简短和可读的:

function recursiveFilter($data, $whiteList)
{
    $results = [];

    foreach ($data as $key => $value) {

        // if the current key is on the whitelist, either as value
        // or as a key (it's a key if it's nested, otherwise a value)
        if(in_array($key, $whiteList) or array_key_exists($key, $whiteList))
        {
            // if the current value is an array and the whitelist
            // has filters for that array, then call this function
            // again with just the relevant portion of data and filters,
            // otherwise just grab the whole value as it is.
            $results[$key] = is_array($value) && isset($whiteList[$key])
                ? recursiveFilter($value, $whiteList[$key])
                : $value;
        }

    }

    return $results;
}
下面是一个工作示例: