remove empty sub arrays value using array_filter

196 Views Asked by At

I add arrays with sub arrays value data into mysql database like this:

{"2":[
{"title":"english title","link":"english url"},
{"title":"","link":""}],
"1":[
{"title":"french title","link":"french url"},
{"title":"","link":""}]}

I try to remove empty sub array value using array_filter and array_map like this:

var_dump(array_filter(array_map('array_filter', $links)));

now, when i check using var_dump I see this result and array_filter and array_map can not remove empty value:

array(2) {
  [2]=>
  array(3) {
    [0]=>
    array(2) {
      ["title"]=>
      string(13) "english title"
      ["link"]=>
      string(11) "english url"
    }
    [1]=>
    array(2) {
      ["title"]=>
      string(0) ""
      ["link"]=>
      string(0) ""
    }
  }
  [1]=>
  array(3) {
    [0]=>
    array(2) {
      ["title"]=>
      string(12) "french title"
      ["link"]=>
      string(10) "french url"
    }
    [1]=>
    array(2) {
      ["title"]=>
      string(0) ""
      ["link"]=>
      string(0) ""
    }
  }
}

in action, how do can i remove empty sub arrays value ?!

UPDATE: i need to this result:

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [title] => english title
                    [link] => english url
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [title] => french title
                    [link] => french url
                )
        )

)
1

There are 1 best solutions below

0
On BEST ANSWER

Your problem is that the items you are trying to filter are not empty (empty($links[2][1]) === false), they are a two element array, so array_filter will not remove them. Instead you need to check that both elements are blank. For example, using array_walk:

array_walk($links, function (&$array) { 
    $array = array_filter($array, function ($obj) {
        return $obj['title'] != '' || $obj['link'] != '';
    });
});

print_r($links);

Output:

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [title] => english title
                    [link] => english url
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [title] => french title
                    [link] => french url
                )
        )
)

Demo on 3v4l.org