$array = array(
'arrays' => array(
'hihi' => array(
'one' => '14000',
'two' => '15000',
'three' => '16000'
),
'huhu' => array(
'one' => '69997',
'two' => '72000',
'three' => '77000'
),
)
);
You can use array_map
function to remove the item two
from the array, and by using closure use ($key)
you can also perform some actions on the element of an array. Read array_map
in detail
$key = 'two';
$result = array(
'arrays' => array_map(
function($item) use ($key) {
unset($item[$key]);
return $item;
},
$array["arrays"]
)
);
print_r($result);
Output
[arrays] => Array
(
[hihi] => Array
(
[one] => 14000
[three] => 16000
)
[huhu] => Array
(
[one] => 69997
[three] => 77000
)
)
Updated Answer
// First array key of the given array which is "arrays"
$getParentKey = array_keys($array);
Output:
Array
(
[0] => arrays
)
// Then, get all values inside "arrays" array which is given below
$getValues = $array[$getParentKey[0]];
Output:
Array
(
[hihi] => Array
(
[one] => 14000
[two] => 15000
[three] => 16000
)
[huhu] => Array
(
[one] => 69997
[two] => 72000
[three] => 77000
)
)
// At last, get "hihi" and "huhu" keys
$getInnerKeys = array_keys($getValues);
Output:
Array
(
[0] => hihi
[1] => huhu
)
// And finally, just unset the items from the array
// "$getInnerKeys[0]" means "hihi" and "$getInnerKeys[1]" means "huhu"
unset($array[$getParentKey[0]][$getInnerKeys[0]]['two']);
unset($array[$getParentKey[0]][$getInnerKeys[1]]['two']);
Complete Code
$getParentKey = array_keys($array);
$getValues = $array[$getParentKey[0]];
$getInnerKeys = array_keys($getValues);
unset($array[$getParentKey[0]][$getInnerKeys[0]]['two']);
unset($array[$getParentKey[0]][$getInnerKeys[1]]['two']);
print_r($array);
Output
[arrays] => Array
(
[hihi] => Array
(
[one] => 14000
[three] => 16000
)
[huhu] => Array
(
[one] => 69997
[three] => 77000
)
)
Without using foreach
loop, you can use array_keys
to remove item from the array.
Another Option
You can also use recursive function, and the recursive function is a function that calls itself, and the function calling will stop on the condition. Read PHP Recursive Functions more in detail.
In below code example, the $count
and $array
are passing to the function once then function is calling itself and the ending point is based on the condition.
$count = 0;
$array = array(
'arrays' => array(
'hihi' => array(
'one' => '14000',
'two' => '15000',
'three' => '16000'
),
'huhu' => array(
'one' => '69997',
'two' => '72000',
'three' => '77000'
),
)
);
incrementCount($count, $array);
function incrementCount($count, $array) {
$getParentKey = array_keys($array);
$getValues = $array[$getParentKey[0]];
$getInnerKeys = array_keys($getValues);
$countInnerKeys = count($getInnerKeys);
if ($count < $countInnerKeys) {
unset($array[$getParentKey[0]][$getInnerKeys[$count]]['two']);
incrementCount($count + 1, $array);
}
else {
print_r($array);
return;
}
}
Calling the function and unsetting two from the array until $countInnerKeys
not reached (means $count
reached to huhu key).