我有下面的多维数组,我想从中删除子数组中的最后两个元素(可能有任意数量的子数组)。
$data= Array
(
[0] => Array
(
[rowdata] => Array
(
[0] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
[] => Overall NPS
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
[1] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
[] => Overall NPS
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
)
[reason] => column values are not correct
)
)
所需的输出:
$data= Array
(
[0] => Array
(
[rowdata] => Array
(
[0] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
)
[1] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
)
)
[reason] => column values are not correct
)
)
我尝试过的
unset ($data[count($data)-2]);
上面的代码不起作用,即它没有删除最后两个元素。我在做什么错?
提前致谢
您的代码无法正常工作,unset ($data[count($data)-2]);
因为count($data)-2 = -1
数组$ data没有键-1,即$ data [-1]。您需要遵循数组示例$ data [0] ['rowdata'] [0] ['ab']。
如果您确定将始终具有该数组“设计”,则可以使用它。
<?php
$data = Array(
0 => Array(
'rowdata' => Array(
0 => Array
(
'DOELGROEP' => 2,
'KANTOOR' => 2,
'OBLIGOCATEGORIE' => 3,
0 => Array
(
1 => 'npsorg',
3 => 'npsdetbe'
)
),
1 => Array
(
'DOELGROEP' => 2,
'KANTOOR' => 2,
'OBLIGOCATEGORIE' => 3,
0 => Array
(
1 => 'npsorg',
3 => 'npsdetbe'
)
)
),
'reason' => 'column values are not correct'
)
);
echo '<pre>';
echo '<h1>before</h1>';
print_r($data);
foreach($data[0]['rowdata'] as $k => $v){
unset($data[0]['rowdata'][$k][0]);
}
echo '<h1>After</h1>';
print_r($data);
//unset($data[0]['rowdata'][0][0]);
// unset($data[0]['rowdata'][1][0]);
更新:您可以,
unset($data[0]['rowdata'][0][0]);
unset($data[0]['rowdata'][1][0]);
或者
foreach($data[0]['rowdata'] as $k => $v){
unset($data[0]['rowdata'][$k][0]);
}
更新的示例:example
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句