1

I have the following array:-

array(3) {
  [1]=>
  array(1) {
    ["A"]=>
    float(5)
  }
  [2]=>
  array(2) {
    ["A"]=>
    float(1)
    ["B"]=>
    float(3)
  }
  [3]=>
  array(2) {
    ["A"]=>
    float(5)
    ["B"]=>
    float(6)
  }
}

And I would like to remove/filter out the nested arrays that only store 1 key so it would end up like this:-

array(2) {
  [2]=>
  array(2) {
    ["A"]=>
    float(1)
    ["B"]=>
    float(3)
  }
  [3]=>
  array(2) {
    ["A"]=>
    float(5)
    ["B"]=>
    float(6)
  }
}

Is there an easy solution/way to do this?

3
  • 4
    array_filter in combination with count Commented Jul 14, 2017 at 10:06
  • 1
    Yes, there is an easy solution/way to do this. Have you tried anything? Commented Jul 14, 2017 at 10:06
  • I used array_filter with the specific keys (["A"]) to check if they are empty and remove them, but I thought this wouldn't be ideal as there could also be a key "C" and I would need to make all of the filters manually. Commented Jul 14, 2017 at 10:15

2 Answers 2

3

Do with simple foreach():-

foreach($array as $key=>$arr){
   if(count($arr) == 1){
      unset($array[$key]);
   }
}

print_r($array);

Output:- https://eval.in/832446

Or using array_filter:-

$newarray = array_filter($array, function($var) {
    return (count($var) !=1);
});

Output:-https://eval.in/832451

Sign up to request clarification or add additional context in comments.

Comments

1

The most trivial method I could think of for this activity is to use the count function of PHP.

Lets assume your array as you have defined and lets call it $originalArray-

array(3) {
  [1]=>
  array(1) {
    ["A"]=>
    float(5)
  }
  [2]=>
  array(2) {
    ["A"]=>
    float(1)
    ["B"]=>
    float(3)
  }
  [3]=>
  array(2) {
    ["A"]=>
    float(5)
    ["B"]=>
    float(6)
  }
}

Now we will iterate through the entire array to find indexes with multiple keys and push them onto a different array.

$new_array = array();

for($i=0;$i<count($originalArray);$i++)
{
   if(count($originalArray[$i])>1)
   {
     array_push($new_array,$originalArray[$i]);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.