php filter array values and remove duplicates from multi dimensional array

前端 未结 4 1912
故里飘歌
故里飘歌 2020-12-21 12:14

Hello all im trying to find duplicate x values from this array and remove them and only leave the unique ones. For example my array is

Array
(
[0] => Arr         


        
4条回答
  •  执笔经年
    2020-12-21 12:40

    When performing iterated checks on arrays, the performance drag with in_array() will progressively worsen as your temporary lookup array increases in size.

    With this in mind, use temporary associative keys to identify subsequent duplicates so that !isset() can be called on your growing result variable. Because php arrays are hash maps, this technique will consistently outperform in_array().

    There IS a gotcha with these temporary keys which applies specifically to your float type values. When floats are used as array keys, php will convert them to integers by truncating ("flooring" not "rounding"). To avoid this unwanted side-effect, prepend a non-numeric character (other than a hyphen, of course) to the temporary keys so that the float becomes a string.

    Code: (Demo)

    $array = [
        ['x' => 0.5, 'y' => 23],
        ['x' => 23, 'y' => 21.75],
        ['x' => 14.25, 'y' => 21.875],
        ['x' => 19.375, 'y' => 21.75],
        ['x' => 9.125, 'y' => 21.875], 
        ['x' => 23, 'y' => 19.625],
        ['x' => 19.375, 'y' => 19.625],
    ];
    
    foreach ($array as $row) {
        if (!isset($result['#' . $row['y']])) {
            $result['#' . $row['y']] = $row;
        }
    }
    var_export(array_values($result));
    

    Output:

    array (
      0 => 
      array (
        'x' => 0.5,
        'y' => 23,
      ),
      1 => 
      array (
        'x' => 23,
        'y' => 21.75,
      ),
      2 => 
      array (
        'x' => 14.25,
        'y' => 21.875,
      ),
      3 => 
      array (
        'x' => 23,
        'y' => 19.625,
      ),
    )
    

    p.s. If dealing with string or integer values as temporay keys there is no need to prepend any characters. If you don't care about removing the temporary keys from the result (because you are only accessing the subarray values "down script", then you don't need to call array_values() after iterating.

提交回复
热议问题