I have an array
$array = array (
'pubMessages' =>
array (
0 =>
array (
'msg' => 'Not bad',
'type' => 'warning',
),
1 =>
array (
'msg' => 'Bad',
'type' => 'error',
),
),
);
To remove the sub array having 'type' => 'error', I use bellow code
$key = array_search('error', $array);
unset($array["pubMessages"][$key]);
The key name of the array pubMessages is changed every time, please tell me how to get this key name dynamically? The count of arrays in pubMessages is also variable.
Get dynamic key name using array_keys()
and then loop through inner array and check if key type
is equal to error
remove it.
$dynamicKey = array_keys($array)[0];
foreach($array[$dynamicKey] as $item){
if ($item['type'] == 'error')
unset($array[$dynamicKey][$key]);
}
Check result in demo
I would use an array_filter()
on this kind of search, like so:
$array = array(
'pubMessages' => array (
0 => array (
'msg' => 'Not bad',
'type' => 'warning'
),
1 => array (
'msg' => 'Bad',
'type' => 'error'
)
)
);
// array_search() will return false. It is not how
// array_search() works on a multi-dimensional array
// $key = array_search('error',$array);
function findError($a) {
return ($a['type'] != 'error');
}
// deal with "unknown" first index / key name issue
$idx = array_keys($array)[0];
$array[$idx] = array_filter($array[$idx],"findError");
var_dump($array);
exit;
And the output will be:
array(1) {
["pubMessages"]=> array(1) {
[0]=> array(2) {
["msg"]=> string(7) "Not bad"
["type"]=> string(7) "warning"
}
}
}
Edit: Added a fix for the unknown key / index issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With