PHP:从嵌套数组中删除值
问题描述:
我从嵌套数组中提取重复值。我想从$ bigarray中删除这些已经被剔除的项目。你会给我一些想法吗?PHP:从嵌套数组中删除值
$bigarray = array(
"430" => array('milk', 'turky', 'apple'),
"433" => array('milk', 'apple', 'orange', 'england'),
"444" => array('milk', 'apple', 'orange', 'spain')
);
$intersected = null;
foreach ($bigarray as $arr) {
$intersected = $intersected ? array_intersect($arr, $intersected) : $arr;
if (!$intersected) {
break; // no reason to continue
}
}
foreach ($intersected as $inter){
foreach ($bigarray as $arr) {
foreach ($arr as $value=>$key) {
if ($key == $inter){
unset($arr[$value]);
}
}
//print_r($arr);
}
}
print_r($bigarray);
答
这是你在找什么?
foreach($bigarray as $id => $arr)
$bigarray[$id] = array_unique($arr);
答
你应该看看array_merge,因为它会合并2列在一起,只保留一个副本。从手册:
如果输入数组具有相同的字符串键,则该键的后面的值 将覆盖前一个。但是,如果数组键 包含数字键,则后面的值不会覆盖原始值 值,但会被追加。
听起来像功课,问题还不是很清楚,所以这是所有我可以提供了。
答
我不完全了解你的问题,但使用array_unique()数组中,我得到了以下的输出:
array(1) {
[430]=>
array(3) {
[0]=>
string(4) "milk"
[1]=>
string(5) "turky"
[2]=>
string(5) "Apple"
}
}
也许这可能是acchieving你想要的方式。
答
function array_unique_nested($arr=array(),$matched=array(),$cm=false){
foreach($arr as $i=>$v){
if (is_array($v)) {$arr[$i]=array_unique_nested($v,$matched,false);
$matched=array_unique_nested($v,$matched,true); continue;}
if (in_array($v,$matched)) {unset($arr[$i]);continue;}
$matched[]=$v;}
if ($cm) return $matched;
else return $arr;}
如果不起作用,这个http://php.net/manual/en/function.array-unique.php的代码片段应该做的伎俩。
if(!function_exists('array_flat'))
{
function array_flat($a, $s = array(), $l = 0)
{
# check if this is an array
if(!is_array($a)) return $s;
# go through the array values
foreach($a as $k => $v)
{
# check if the contained values are arrays
if(!is_array($v))
{
# store the value
$s[ ] = $v;
# move to the next node
continue;
}
# increment depth level
$l++;
# replace the content of stored values
$s = array_flat($v, $s, $l);
# decrement depth level
$l--;
}
# get only unique values
if($l == 0) $s = array_values(array_unique($s));
# return stored values
return $s;
} # end of function array_flat(...
}
答
可以使用array_unique($阵列[摘要$ sort_flags改变]功能。如果不指定可选sort_flag,该函数将比较值转换一切字符串。如果你具有比阵列中的字符串的其它值,则可以指定sort_flag是下列值之一
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
从PHP.net
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
实施例
的更多信息,请参阅 http://php.net/manual/en/function.array-unique.php
说有什么错示例代码将是一个良好的开端... – 2012-02-03 14:33:19
是的,我的“M提取重复,但不能删除它们。我想从原始数组中提取并删除它们。 – user973067 2012-02-03 14:35:13
一旦你知道了重复项是什么(循环退出后'$ intersected'),你就可以得到这个结果并返回到原始数组并删除这些值。 – 2012-02-03 14:37:13