这里有一个函数,我从嵌套数组中删除一些键。我怎样才能优化它,让它看起来更漂亮,更有效率呢?
$data是数组类型,包含以下内容:
$data = [
'0' => [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
],
'1' => [
'key1' => 'value4',
'key2' => 'value5',
'key3' => 'value6'
],
];
$column(s)是数组类型,包含我想从数组数组中删除的键
$columns = ['key1', 'key2'];
用PHP编写的函数的一部分是:
***
$newData = [];
foreach ($data as $row) {
$newRow = array_diff_key($row,array_flip($columns));
array_push($newData, $newRow);
}
return $newData;
***
预期结果:
$data = [
'0' => [
'key1' => 'value1'
],
'1' => [
'key1' => 'value4'
],
];
功能运行良好,但看起来很糟糕:D
希望这能解决你的问题
function delKey ($data, $columns){
$result = array();
for ($i = 0; $i<count($data); $i++){
$a = $data["$i"];
foreach ($columns as $key){
if (isset($a[$key])){
unset($a[$key]);
}
}
$result["$i"] = $a;
}
return $result;
}