php 多维数组筛选并删除重复项

xxb16uws  于 2023-05-21  发布在  PHP
关注(0)|答案(1)|浏览(141)

我下面有两个多维数组。

$filter=array(1,3);

$data= array( 
    array( "name"=>'milind', "flt"=>array(1,2,3,4) ), 
    array( "name"=>'bhuvad', "flt"=>array(3,4) ) 
);

我尝试了下面的代码过滤器

$count = count($data);
$new = array();
for($x=0;$count>$x;$x++){ 
    foreach($data[$x]["flt"] as $flt){  
        if(in_array($flt,$filter)){ 
            $new[]=$data[$x]; 
        } 
    } 
}
print_r($new);

得到的结果类似

array( 
    [0] => Array ( [name] => milind [flt] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ), 
    [1] => Array ( [name] => milind [flt] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ),
    [2] => Array ( [name] => bhuvad [flt] => Array ( [0] => 3 [1] => 4 ) ) 
)

我想要的结果是

array( 
    [0] => Array ( [name] => milind [flt] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ), 
    [1] => Array ( [name] => bhuvad [flt] => Array ( [0] => 3 [1] => 4 ) ) 
)

如果我使用array_unique()来移动重复的数组,得到下面的结果。

array( 
    [0] => Array ( [name] => milind [flt] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ) 
)
2ul0zpep

2ul0zpep1#

我希望这能帮助你。

// Sample multidimensional array
$array = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Jane'),
    array('id' => 1, 'name' => 'John'),
    array('id' => 3, 'name' => 'Bob'),
    array('id' => 2, 'name' => 'Jane'),
);

// Remove duplicates based on the 'id' key
$filteredArray = array_unique($array, SORT_REGULAR);

// Remove empty elements
$filteredArray = array_filter($filteredArray);

// Reindex the array
$filteredArray = array_values($filteredArray);

// Print the filtered array
print_r($filteredArray);

相关问题