排序,删除数组中的重复值和空值

时间:2014-06-24 11:49:53

标签: php arrays sorting multidimensional-array

我想要排序,删除下面数组的重复和空值

更新  到目前为止我已经尝试过了,

 $cat_ids =
  Array
    (
        [0] => 9,12,
        [1] => 5,6,10,13,7,8,14
        [2] => 13,
        [3] => 
        [4] => 
        [5] => 14,
        [6] => 15,
    );

$cat_ids = array_filter($cat_ids);

$cat_ids = array_map("unserialize", array_unique(array_map("serialize", $cat_ids)));
print_r($cat_ids);

我期望的数组应该是这样的,

array(
  [0] => 5,6,7,8,9,10,12,13,14,15
);

 array(
            [0] => 5
            [1] => 6
            [2] => 7
            [3] => 8
            [4] => 9
            [5] => 10
            [6] => 12
            [n] => v ...
        );

所以它应该可以轻松访问这个数组中的任何元素..什么是最好的方法...?请帮帮我们..

2 个答案:

答案 0 :(得分:3)

$array = array (
    0 => '9,12',
    1 => '5,6,10,13,7,8,14',
    2 => '13',
    3 => '',
    4 => '',
    5 => '14',
    6 => '15'
);

// turn strings into arrays with explode
$array = array_map( function( $item ) { return explode( ',', $item ); }, $array );
// merge all arrays
$array = call_user_func_array( 'array_merge', $array );
// remove empty and duplicate values    
$array = array_filter( array_unique( $array ) );
// sort 
sort( $array );

print_r( $array );
/* output: 
Array
(
    [0] => 5
    [1] => 6
    [2] => 7
    [3] => 8
    [4] => 9
    [5] => 10
    [6] => 12
    [7] => 13
    [8] => 14
    [9] => 15
)
*/

答案 1 :(得分:1)

试试这个希望这有帮助

 $a = Array
    (
         "9,12" , "5,6,10,13,7,8,14" , "13," , "" , "" , "14," , "15,"
    );


    echo '<pre>';
    print_r($a);

    $b = array_filter($a);

    print_r($b);


    $str = implode(',' , $b);
    echo $str;

    $exp = explode(',',$str);
    echo '<br>';
    print_r(array_filter($exp));