[英]Remove specific records from associative array key in php
Hi I have an array that contains two arrays that has the following structure: 嗨,我有一个包含两个具有以下结构的数组的数组:
categories [
"lvl0" => array:2 [
0 => "Cleaning"
1 => "Bread"
]
"lvl1" => array:2 [
0 => null
1 => "Bread > rolls"
]
]
I would like to remove any records of NULL from the 'lvl1' array but have not been able to find the correct method to do this. 我想从“ lvl1”数组中删除任何NULL记录,但一直无法找到正确的方法来执行此操作。
I have tried: 我努力了:
array_filter($categories['lvl1'])
But this also removes all records associated to lvl1 and not just the NULL ones. 但这也会删除与lvl1相关的所有记录,而不仅仅是NULL。
Any help would be greatly appreciated. 任何帮助将不胜感激。
Thanks 谢谢
array_filter()
takes a callback as the second argument. array_filter()
将回调作为第二个参数。 If you don't provide it, it returns only records that aren't equal to boolean false
. 如果不提供,则它仅返回不等于boolean false
。 You can provide a simple callback that removes empty values. 您可以提供一个简单的回调来删除空值。
array_filter()
also uses a copy of your array (rather than a reference), so you need to use the return value. array_filter()
也使用数组的副本(而不是引用),因此您需要使用返回值。
For instance: 例如:
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$lvl1 = array_filter($categories['lvl1'], function($value) {
return !empty($value);
});
var_dump($lvl1);
That will return: 那将返回:
array(1) {
[1] =>
string(13) "Bread > rolls"
}
I was having the same issue on my last working day.Generally for associative array array_filter()
needs the array key to filter out null
, false
etc values. 我在上一个工作日遇到同样的问题。通常对于关联数组array_filter()
需要使用数组键来过滤出null
, false
等值。 But this small function help me to filter out NULL
values without knowing the associative array key. 但是,这个小函数可以帮助我在不知道关联数组键的情况下过滤掉NULL
值。 Hope this will also help you, https://eval.in/881229 希望对您有所帮助, https://eval.in/881229
Code: 码:
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$result = array_filter_recursive($categories);
print '<pre>';
print_r($result);
print '</pre>';
Output: 输出:
(
[lvl0] => Array
(
[0] => Cleaning
[1] => Bread
)
[lvl1] => Array
(
[1] => Bread > rolls
)
)
Ref: http://php.net/manual/en/function.array-filter.php#87581 参考: http : //php.net/manual/zh/function.array-filter.php#87581
Robbie Averill在以下内容中对我的帖子进行了评论,从而解决了该问题:
$categories['lvl1'] = array_filter($categories['lvl1']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.