如何在php中搜索多维数组中的针?

问题描述 投票:1回答:2

我有一些不同类型的php数组,它们在任何嵌套级别都可以包含敏感数据。我想取消设置此敏感键。我应该如何处理?

例如敏感数据密钥可以是account_noacc_no

示例请求数组1:

[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]

此数组应变为

[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]

示例请求数组2:

  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]

此数组应成为

[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]
php arrays laravel security logging
2个回答
1
投票

递归函数可为您提供任何级别的嵌套:

$test = array(
  'Client' => 'asdasd',
  'acc_no' => 'asdasd',
  'test' => array(
    'acc_no' => 'asdd',
    'llaa' => 'asdasd'
  )
);

$delete_keys = array(
  'acc_no',
  'account_no'
);


function deleteSensitiveKeys( &$array, $delete_keys )  {
  foreach( $array as $key => &$value ) {
    if( is_array( $value ) )  {
      deleteSensitiveKeys( $value, $delete_keys );
    } else {
      if( in_array( $key, $delete_keys )  ) {
        unset($array[$key]);
      }
    }
  }
}

deleteSensitiveKeys( $test, $delete_keys );

echo "<pre>";
print_r( $test );
echo "</pre>";

0
投票

无循环的解决方案

在第一个数组中:

unset($arr['acc_no']);

在第二个数组中:

unset($arr['customer_details']['account_no']);

使用循环的解决方案

第一个数组:

foreach($arr1 as $key => $value) {
   if($key === 'acc_no') {
      unset($arr1['acc_no']);
   }
}

第二数组:

foreach($arr2 as $key => $value) {
    if($key === 'customer_details') {
        unset($arr2['customer_details']['account_no']);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.