PHP: remove element from multidimensional array (by key) using foreach
I got a multidimensional array. From each subarray, I would like to delete / remove values ββby index 1. My data is $ array.
Array
(
[3463] => Array
(
[0] => 1
[1] => 2014
[context] => 'aaa'
)
[3563] => Array
(
[0] => 12
[1] => 2014
[context] => 'aaa'
)
[2421] => Array
(
[0] => 5
[1] => 2014
[context] => 'zzz'
)
)
I would like to remove each item at index '1' from the subarrays. Desired output:
Array
(
[3463] => Array
(
[0] => 1
[context] => 'aaa'
)
[3563] => Array
(
[0] => 12
[context] => 'aaa'
)
[2421] => Array
(
[0] => 5
[context] => 'zzz'
)
)
Why doesn't it work?
foreach ($data as $subArr) {
foreach ($subArr as $key => $value) {
if ($key == '1') {
unset($subArr[$key]);
}
}
}
I am sorry if this problem is trivial for you guys.
easy way !? you can only do it with one foreach!
foreach ($data as $key => $subArr) {
unset($subArr['1']);
$data[$key] = $subArr;
}
you are making changes to subarray instead of main one, try this, might help
foreach ($data as $key => $subArr) {
unset($data[$key][1]);
}
try this:
<?php
$data = Array
(
'3463' => Array
(
'0' => 1,
'1' => 2014,
'context' => 'aaa'
),
'3563' => Array
(
'0' => 12,
'1' => 2014,
'context' => 'aaa'
),
'2421' => Array
(
'0' => 5,
'1' => 2014,
'context' => 'zzz'
)
);
foreach ($data as $k=>$subArr) {
foreach ($subArr as $key => $value) {
if ($key == '1') {
unset($data[$k][$key]);
}
}
}
print_r($data);// display the output
This does not work, because the $subArr
outer foreach
contains copies of the values $data
, while the inner foreach
changes these copies, leaving $data
them untouched.
You can fix this by instructing PHP
to make $subArr
references to the original values ββstored in $data
:
foreach ($data as &$subArr) {
foreach ($subArr as $key => $value) {
if ($key == '1') {
unset($subArr[$key]);
}
}
}
Another option is to use a function array_map()
. It uses a callback function that can check (and change) each value $data
and returns a new array.
$clean = array_map(
function (array $elem) {
unset($elem['1']); // modify $elem
return $elem; // and return it to be put into the result
},
$data
);
print_r($clean);