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

时间:2015-01-20 12:02:51

标签: php arrays

我有一个这样的数据数组:

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级深度。

1 个答案:

答案 0 :(得分:0)

如果你不知道嵌套数组有多深,那么递归解决方案可能是合适的。也许有更好的,但我认为这很短且可读:

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

以下是一个有效的例子:http://codepad.viper-7.com/16JIJf