I got multidimensional array. From each subarray, I would like to remove / unset values with index 1. My array $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'
)
)
I would like to remove every element with index '1' from subarrays. Desired output is:
Array
(
[3463] => Array
(
[0] => 1
[context] => 'aaa'
)
[3563] => Array
(
[0] => 12
[context] => 'aaa'
)
[2421] => Array
(
[0] => 5
[context] => 'zzz'
)
)
Why this does not work?
foreach ($data as $subArr) {
foreach ($subArr as $key => $value) {
if ($key == '1') {
unset($subArr[$key]);
}
}
}
I'm sorry if this problem is trivial for you guys.
try this:
easy way!? you can do this just with one foreach!
It does not work because
$subArr
from the outerforeach
contains copies of the values of$data
and the innerforeach
modifies these copies, leaving$data
not touched.You can fix that by telling
PHP
to make$subArr
references to the original values stored in$data
:Another option is to use function
array_map()
. It uses a callback function that can inspect (and modify) each value of$data
and it returns a new array.you are making changes in subarray instead of main one try this may help