Search code examples
phparrayslaravelarray-filterlaravel-collection

Laravel collection remove all keys if in any of them has value NULL


For some calculation i need to remove all keys in whole collection if he has in any array NULL value.

for example

[
'butter'=>['iron'=>5, 'magnesium'=>3.5],
'salt'=>['iron'=>2, 'magnesium'=>2],
'egg'=>['iron'=>4, 'magnesium'=>NULL]
]

Because one of item is empty i need new array to be like this

[
'butter'=>['iron'=>5],
'salt'=>['iron'=>2],
'egg'=>['iron'=>4]
]

I'm not sure i can accomplish this with Laravel collection, maybe there is better way with pure php.

P.S. Sorry my english is not so good


Solution

  • OK i make this code and this work like i want, but i think its ugly is there some better way with Laravel collection or in pure php

    $foods=[
    'butter'=>['iron'=>5, 'magnesium'=>3.5, 'calcium'=>3],
    'salt'=>['iron'=>2, 'magnesium'=>2, 'calcium'=>6],
    'egg'=>['iron'=>4, 'magnesium'=>NULL, 'calcium'=>5]
    ];
    
    $nutrientsWithNull=[];
    
    foreach($foods as $food)
    {
        foreach($food as $key=>$value){
            if(is_null($value)&&!in_array($key, $nutrientsWithNull))
            {
                $nutrientsWithNull[]=$key;
            }
        }
    }
    
    foreach($foods as $key=>$food)
    {
        foreach($nutrientsWithNull as $withNull ) {
           unset($foods[$key][$withNull]);
        }
    
    }
    
    print_r($foods);
    

    and result is

    $foods=[
    'butter'=>['iron'=>5, 'calcium'=>3],
    'salt'=>['iron'=>2, 'calcium'=>6],
    'egg'=>['iron'=>4, 'calcium'=>5]
    ];