多维数组呢?我为此解决方案研究了几个小时,但没有找到最佳解决方案。所以,我自己写的
function allow_keys($arr, $keys)
{
$saved = [];
foreach ($keys as $key => $value) {
if (is_int($key) || is_int($value)) {
$keysKey = $value;
} else {
$keysKey = $key;
}
if (isset($arr[$keysKey])) {
$saved[$keysKey] = $arr[$keysKey];
if (is_array($value)) {
$saved[$keysKey] = allow_keys($saved[$keysKey], $keys[$keysKey]);
}
}
}
return $saved;
}
用途:例子
$array = [
'key1' => 'kw',
'loaa'=> ['looo'],
'k' => [
'prope' => [
'prop' => ['proo', 'prot', 'loolooo', 'de'],
'prop2' => ['hun' => 'lu'],
],
'prop1' => [
],
],
];
调用:示例
allow_keys($array, ['key1', 'k' => ['prope' => ['prop' => [0, 1], 'prop2']]])
输出:
Array ( [key1] => kw [k] => Array ( [prope] => Array ( [prop] => Array ( [0] => proo [1] => prot ) [prop2] => Array ( [hun] => lu ) ) ) )
所以你从多维数组中只得到需要的键。它不仅限于“多维”,您可以通过传递一个数组来使用它
['key1', 'loaa']
你得到的输出:
Array ( [key1] => kw [loaa] => Array ( [0] => looo ) )
干杯!