oliverbj
oliverbj

Reputation: 6050

PHP/Laravel - Get the key name from array where key have data

I have the below array called $items:

array:3 [▼
  0 => array:9 [▼
    "qty" => 1
    "name" => "Guide, interlocked slats, R Commodity code: 39239000 / Country of origin: PL. Delivery note 838174147 from 12.09.2019 PC 1,50/ 10"
  ]
  1 => array:9 [▼
    "qty" => null
    "name" => "Guide, interlocked slats, L Commodity code: 39239000 / Country of origin: PL. Delivery note 838174147 from 12.09.2019 PC"
  ]
  2 => array:9 [▼
    "qty" => null
    "name" => "Bottom groove set L + R Commodity code: 39239000 / Country of origin:"
  ]
]

I am trying to find the specific key, that has a value in all three subarray. In this case, this would be the key name, as this specific key has a value in all three arrays.

I have tried to write a function for this, as you can see below:

function getKeysWithData(array $items): array
{
    //Get the key(s) that has region data for all items.
    $keysWithData = collect($items)->map(function ($item) {
        return array_keys(collect($item)->filter()->toArray()); //filter will remove all null
    })->flatten()->unique()->toArray();
   
}

The above function returns an array, containing the name of the keys that has some values. So for the above $items, it will return:

array:2 [▼
  0 => "qty"
  1 => "name"
]

This is because both qty and name contain some value at some point. However, it should only return name.

How can I do, so it will only return the name of the key(s), that has data in all arrays?

Upvotes: 0

Views: 2124

Answers (2)

Akshay Hiremath
Akshay Hiremath

Reputation: 61

Use two times foreach loop for two dimension array. ex: '''

       foreach($array as $k=>$v){
        //$k is 0
        //$v contains another inside array so use another foreach loop
         foreach($v as $x => $y){
    
       if($y != "null" && $x != "null" && $x == "name"){
    echo $x;  //it contains key ex : name
    echo $y;  //it contains value ex : 1
   $z[$x]=$y; // it contains only name key
    }
          
        }
        
        }

'''

Upvotes: 0

u_mulder
u_mulder

Reputation: 54841

Though this is not laravel and all this functional style, but at least it loops over your array only once:

// Take first element so as to know what keys do we have:
$keys = $items[0];
foreach ($items as $item) {
    foreach ($item as $key => $value) {
        if ($value === null) {
            // unset the key which has NULL value
            unset($keys[$key]);
        }
        
        // if there no keys left - break all loops
        if (empty($keys)) {
            break 2;
        }
    }
}
print_r(array_keys($keys));

And da fiddle.

Upvotes: 1

Related Questions