display the array which meets only this condition in php

319 Views Asked by At

i have a multidimensional array, and iam looping inside to get the sub-arrays: so i have a sub-array lie this:

array (
  0 => 
  array (
    'norm_value' => 2.5,
  ),
  1 => 
  array (
    'norm_value' => 7.01,
  ),
  2 => 
  array (
    'norm_value' => 0.0,
  ),
  3 => 
  array (
    'norm_value' => 4.167,
  ),
  4 => 
  array (
    'norm_value' => 0.0,
  ),
)

array (
  0 => 
  array (
    'norm_value' => 0.0,
  ),
  1 => 
  array (
    'norm_value' => 0.0,
  ),
  2 => 
  array (
    'norm_value' => 0.0,
  ),
  3 => 
  array (
    'norm_value' => 1.267,
  ),
  4 => 
  array (
    'norm_value' => 0.0,
  ),
)

array (
  0 => 
  array (
    'norm_value' => 0.0,
  ),
  1 => 
  array (
    'norm_value' => 0.0,
  ),
  2 => 
  array (
    'norm_value' => 0.0,
  ),
  3 => 
  array (
    'norm_value' => 0.0,
  ),
  4 => 
  array (
    'norm_value' => 0.0,
  ),
)

array (
  0 => 
  array (
    'norm_value' => 3.54,
  ),
  1 => 
  array (
    'norm_value' => 2.04,
  ),
  2 => 
  array (
    'norm_value' => 0.673,
  ),
  3 => 
  array (
    'norm_value' => 8.546,
  ),
  4 => 
  array (
    'norm_value' => 0.0,
  ),
)

So from the above set of arrays, i want remove the complete array which has atleast one non-zero value or all zero values, from the above case i want to remove the complete second array(this has only one non-zero value) and third array(this has all zero values) array , other two (first and last) arrays are to be displayed as it is.

i tried this pie of code, but didnt work for me:

array_filter(array_column($array, 'norm_value'),function($n){
    return ( count ($n > 0) <= 1) ;
});

please let me know if i am missing anything here or any syntax issues to fix this problem Thanks is advance.

1

There are 1 best solutions below

0
nice_dev On BEST ANSWER

We would loop over each subarray and count how many norm_value has 0.0. If the count matches the size or size-1, then we unset that index.

$epsilon = 0.00001;

foreach($arr as $index => $subarray){
    $count = 0;
    foreach($subarray as $norm_data){
        if(abs($norm_data['norm_value'] - 0.0) < $epsilon) $count++;
    }

    if($count === count($subarray) || $count == count($subarray)-1){
        unset($arr[$index]);
    }
}

print_r($arr);

Demo: https://3v4l.org/futQ8