隔离逗号分隔的值,删除重复项和空值,然后排序


Isolate comma-separated values, remove duplicates and empty values, then sort

我想从逗号分隔值的平面数组中隔离单个值。

我还想删除任何空字符串和重复的值,然后以升序方式对结果排序。

样本输入:

$cat_ids = [
    '9,12',
    '5,6,10,13,7,8,14',
    '13',
    '',
    '',
    '14',
    '15'
];

我已经试过了,

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

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

['5,6,7,8,9,10,12,13,14,15']

[
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '12',
    '13',
    '14',
    '15',
];

因此数组中的任何元素都可以轻松访问

$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
)
*/

试试这个,希望能有所帮助

 $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));

用逗号连接以逗号分隔的字符串。然后用一个或多个逗号分隔。最后,从低到高排序。

没有迭代爆炸,没有array_filter,没有合并。

代码(演示):

$result = array_unique(
    preg_split(
        '/,+/',
        implode(',', $array)
    )
);
sort($result);
var_export($result);