leym
leym

Reputation: 33

PHP - How to get "upper" key from value in a nested array?

$arrayTypesAndSubtypes = Account::getTypesAndSubtypes();
$subtype = $request->input('subtype');

Here's a dd of $arrayTypesAndSubtypes from which I want to get the "upper (?) key" for a given value.

array:2 [▼
  "REVENUE" => array:1 [▼
    0 => "REVENUE"
  ]
  "ASSET" => array:1 [▼
    0 => "BANK_ACCOUNT"
  ]
]

Here, the following returns false (because Array_search() will return 0 for either REVENUE or BANK_ACCOUNT ; however, what I'm looking for is to return either REVENUE or ASSET (what I'm calling the "upper key" - is there a more proper term for that?).

Any help would be appreciated!

Upvotes: 2

Views: 322

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78984

Assuming they are in the 0 key, just extract that column, combine with the current keys and search:

$key = array_search('BANK_ACCOUNT', array_combine(array_keys($array), 
                                                  array_column($array, 0)));

var_dump(key);  //should return ASSET

Or if you have multiple under each key, then loop:

$key = false;
foreach($array as $key => $values) {
    if(array_search('BANK_ACCOUNT', $values)) { // or in_array('BANK_ACCOUNT', $values)
        break;
    }
}

var_dump($key);  //should return ASSET

Upvotes: 2

Jeto
Jeto

Reputation: 14927

As an alternative, you could "flatten" your array first using array_map:

$flattened = array_map(fn(array $val) => $val[0], $arr));

Then simply array_search it:

$key = array_search('BANK_ACCOUNT', $flattened);  // ASSET

Upvotes: 0

Related Questions