我有一个数组,里面还有其他数组,我想删除具有键“ PTemp_C_Avg”的元素
尝试通过创建遍历原始数组并消除分配的键(在这种情况下为PTemp_C_Avg)的函数来做到这一点。但是,这并没有删除特定元素。
//arrProvAvg array
Array
(
[0] => Array
(
[PTemp_C_Avg] => 17.28
[T0_10cm_Avg] => 22.58
[T1_1m_Avg] => 27.91
[T2_2m_Avg] => 31.95
[T3_3m_Avg] => 36.32
[T4_4m_Avg] => 41.73
[T5_5m_Avg] => 45.78
[T6_6m_Avg] => 48.55
[T7_7m_Avg] => 53.48
[T7_5_7_5m_Avg] => 47.82
)
[1] => Array
(
[PTemp_C_Avg] => 14.2
[T0_10cm_Avg] => 20.94
[T1_1m_Avg] => 27.36
[T2_2m_Avg] => 32.12
[T3_3m_Avg] => 36.33
[T4_4m_Avg] => 41.4
[T5_5m_Avg] => 46.58
[T6_6m_Avg] => 48.8
[T7_7m_Avg] => 52.69
[T7_5_7_5m_Avg] => 48.9
)
[2] => Array
(
[PTemp_C_Avg] => 11.83
[T0_10cm_Avg] => 20.23
[T1_1m_Avg] => 26.9
[T2_2m_Avg] => 32.39
[T3_3m_Avg] => 36.95
[T4_4m_Avg] => 41.48
[T5_5m_Avg] => 46.41
[T6_6m_Avg] => 48.82
[T7_7m_Avg] => 52.58
[T7_5_7_5m_Avg] => 49.42
)
)
function eliminaClave($arrOriginal, $key){
foreach($arrOriginal as $clave => $valor){
foreach($valor as $c => $v){
unset($v[$key]);
}
}
return $arrOriginal;
}
//Call the eliminaClave function
$arrPromAvg = eliminaClave($arrPromAvg, "PTemp_C_Avg");
这是我解释的输出
Array
(
[0] => Array
(
[T0_10cm_Avg] => 22.58
[T1_1m_Avg] => 27.91
[T2_2m_Avg] => 31.95
[T3_3m_Avg] => 36.32
[T4_4m_Avg] => 41.73
[T5_5m_Avg] => 45.78
[T6_6m_Avg] => 48.55
[T7_7m_Avg] => 53.48
[T7_5_7_5m_Avg] => 47.82
)
[1] => Array
(
[T0_10cm_Avg] => 20.94
[T1_1m_Avg] => 27.36
[T2_2m_Avg] => 32.12
[T3_3m_Avg] => 36.33
[T4_4m_Avg] => 41.4
[T5_5m_Avg] => 46.58
[T6_6m_Avg] => 48.8
[T7_7m_Avg] => 52.69
[T7_5_7_5m_Avg] => 48.9
)
[2] => Array
(
[T0_10cm_Avg] => 20.23
[T1_1m_Avg] => 26.9
[T2_2m_Avg] => 32.39
[T3_3m_Avg] => 36.95
[T4_4m_Avg] => 41.48
[T5_5m_Avg] => 46.41
[T6_6m_Avg] => 48.82
[T7_7m_Avg] => 52.58
[T7_5_7_5m_Avg] => 49.42
)
)
带有“ PTemp_C_Avg”的元素已被删除
答案 0 :(得分:2)
使用单个foreach()
和unset()
怎么样?
function eliminaClave($arrOriginal, $key){
foreach($arrOriginal as $clave => $valor){
unset($valor['PTemp_C_Avg']);
$arrOriginal[$clave] = $valor;
}
return $arrOriginal;
}
答案 1 :(得分:1)
这里没有循环,
function eliminaClave($arr, $key)
{
return array_map(function ($item) use ($key) {
unset($item[$key]); // unsetting elements
return $item; // saving back changed item
}, $arr);
}
Demo。
答案 2 :(得分:0)
您不需要第二个foreach。
<?php
$a[0]['PTemp_C_Avg']='1';
$a[0]['foo']='1';
$a[1]['PTemp_C_Avg']='2';
$a[1]['foo']='1';
foreach($a as $k=> $b){
unset($a[$k]['PTemp_C_Avg']);
}
print_r($a);
输出:
Array (
[0] => Array
(
[foo] => 1
)
[1] => Array
(
[foo] => 1
)
)