我有以下多维数组:
$subregion = [
[
"subregion_id" => "8",
"subregion_name" => "NORTH_AMERICA",
"subregion_abbr" => "US"
],
[
"subregion_id" => "9",
"subregion_name" => "NORTH_AMERICA",
"subregion_abbr" => "CA"
],
[
"subregion_id" => "6",
"subregion_name" => "WE",
"subregion_abbr" => "South"
],
[
"subregion_id" => "0",
"subregion_name" => null,
"subregion_abbr" => null
],
[
"subregion_id" => "5",
"subregion_name" => "WE",
"subregion_abbr" => "North"
],
[
"subregion_id" => "0",
"subregion_name" => null,
"subregion_abbr" => null
]
];
我想通过它的值来唯一这个数组,所以我测试了以下内容:
$subregion = array_map("unserialize", array_unique(array_map("serialize", $subregion)));
$subregion = array_intersect_key($subregion, array_unique(array_map('serialize', $subregion)));
$subregion_unique = array_unique($subregion, SORT_REGULAR);
它们都工作(一个接一个地尝试)并产生相同的输出:
$subregion = [
[
"subregion_id" => "8",
"subregion_name" => "NORTH_AMERICA",
"subregion_abbr" => "US"
],
[
"subregion_id" => "9",
"subregion_name" => "NORTH_AMERICA",
"subregion_abbr" => "CA"
],
[
"subregion_id" => "6",
"subregion_name" => "WE",
"subregion_abbr" => "South"
],
[
"subregion_id" => "5",
"subregion_name" => "WE",
"subregion_abbr" => "North"
],
[
"subregion_id" => "0",
"subregion_name" => null,
"subregion_abbr" => null
]
];
我想去掉数组上的null
值,因为它们不应该在那里。所以我尝试了这个其他的解决方案(在这里找到):
private function is_not_null($var)
{
return !is_null($var);
}
$unique = array_filter($subregion_unique, 'is_not_null');
但是奇怪的是$unique
的输出和之前完全一样,为什么?我在这里错过了什么?
注意我忘了说应该兼容PHP 5.3.10+
更新:test1
按照@abracadaver的说明,这是我尝试过的:
$unique = array_map('unserialize', array_unique(array_map('serialize', $subregion)));
$unique = array_map(function($v) { return array_filter($v, 'is_not_null'); }, $unique);
我已经改变了上面的函数is_not_null($var)
,以这种方式返回结果:
return null !== $var;
结果是包含null
值的数组。
PS:也许标题不准确,帖子被关闭或标记为重复,如果是这样,请建议我一个更好的标题或如果你可以自己更改。
不知道为什么要写这么多代码。这一行得到一个唯一的数组:
$unique = array_map("unserialize", array_unique(array_map("serialize", $subregion)));
然后用当前函数过滤出null
:
$unique = array_map(function($v) { return array_filter($v, 'is_not_null'); }, $unique);
如果你不关心0
是否被删除,那么它甚至更短,你不需要你的函数:
$unique = array_map(function($v) { return array_filter($v); }, $unique);
那么你知道你将有一个空的子数组,所以你可以过滤它:
$unique = array_filter($unique);
SORT_REGULAR
在这里没有区别,但是当它可能的时候,或者如果你需要一个不同的标志,你可以把它添加到上面的array_unique()
:
$unique = array_map("unserialize",
array_unique(array_map("serialize", $subregion), SORT_REGULAR));
这段代码将帮助您去掉null:
foreach($subregion_unique as $key => $item) {
foreach($item as $itemKey => $value) {
if($value === null) {
unset($subregion_unique[$key][$itemKey];
}
}
}
php>=5.3这样使用
$unique = array_map(function($a){
return array_filter($a);
},$subregion);
过滤每个子数组
还是
foreach($subregion as &$a){
$a=array_filter($a);
}
如果"subregion_id"="0"可以跳过