Unset array key if all array child values are empty

136 Views Asked by At

I've an array with the following structure:

array(
    "0" => array(
        "0" => array(
            '0' => array('value' => 'value'),
            '1' => array('value' => ''),
            '2' => array('value' => ''),
        ),
        "1" => array(
            '0' => array('value' => 'abc'),
            '1' => array('value' => 'lorem'),
            '2' => array('value' => ''),
        )
    ),
    "1" => array(
        "0" => array(
            '0' => array('value' => ''),
            '1' => array('value' => 'hgjklo'),
            '2' => array('value' => ''),
        ),
        "1" => array(
            '0' => array('value' => 'abcdef'),
            '1' => array('value' => 'value'),
            '2' => array('value' => ''),
        )
    ),
)

and what I'm trying to accomplish is to remove all keys for the "empty" value, but only if the value is empty in all* child-arrays inside the main-array.

Expected output:

array(
    "0" => array(
        "0" => array(
            '0' => array('value' => 'value'),
            '1' => array('value' => ''),
        ),
        "1" => array(
            '0' => array('value' => 'abc'),
            '1' => array('value' => 'lorem'),
        )
    ),
    "1" => array(
        "0" => array(
            '0' => array('value' => ''),
            '1' => array('value' => 'hgjklo'),
        ),
        "1" => array(
            '0' => array('value' => 'abcdef'),
            '1' => array('value' => 'value'),
        )
    ),
)

NOTE: child-array position 2 was removed, because it was empty in all the main-array positions.

Does anyone have a great idea how this can be done without a complex logic of foreach's?

1

There are 1 best solutions below

1
On

As expressed, the structure of the data is not helpful. I agree array_ functions are generally great, but they work better with structures that make sense.

If for example you removed just a little of the useless cruft, to achieve an array like the following one:

$foo = array(
    "0" => array(
        "0" => array(
            '0' => 'value',
            '1' => '',
            '2' => '',
        ),
        "1" => array(
            '0' => 'abc',
            '1' => 'lorem',
            '2' => '',
        )
    ),
    "1" => array(
        "0" => array(
            '0' =>  '',
            '1' => 'hgjklo',
            '2' => ''
        ),
        "1" => array(
            '0' => 'abcdef',
            '1' => 'value',
            '2' => ''
        )
    ),
);

You could then do something like:

<?php
$uids = array_fill_keys(array_keys($foo[0][0]), 0);

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($foo));
foreach($it as $k =>$v) {
  if (!empty($v)) $uids[$k]++;
}
var_dump($uids);

/*
The value here shows the number of non empty values in the set per key.
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(3)
  [2]=>
  int(0)
}

Clean the array up more and it just gets easier.