user529649
user529649

Reputation:

Return the first level key when a column value is found in a 2d array

I have this:

Array
(
    [carx] => Array
        (
            [no] => 63
       
        )

    [cary] => Array
           (
           [no] => 64
   
           )
)

How can I find the key carx when I have the no=63? I know how to use array_search() but this one is a bit tricky.

Like I can find key name id while I have 63 But this one is a bit tricky.

Upvotes: 0

Views: 8940

Answers (4)

mickmackusa
mickmackusa

Reputation: 47894

When searching for the full row value, then array_search() is appropriate. The function will return false if there is no match. Demo

$array = [
    'carx' => ['no' => 63],
    'cary' => ['no' => 64],
];

var_export(
    array_search(['no' => 63], $array)
);
// 'carx'

From PHP8.4, array_find_key() has the same highly performant mechanism, but offers more granular tooling and it returns null if there is no match. Demo

var_export(
    array_find_key(
        $array,
        fn($row) => $row['no'] === 63
    )
);
// 'carx'

Upvotes: 0

Evolutionary
Evolutionary

Reputation: 41

Is this of any use? I use it to do generic searches on arrays and objects. Note: It's not speed/stress tested. Feel free to point out any obvious problems.

function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
    $result             = false;
    $search_occurences  = 0;
    $output_value       = null;
    if($occurence < 1){ $occurence = 1; }
    foreach($haystack as $key => $value){
        if($key == $search_key){
            $search_occurences++;
            if($search_occurences == $occurence){
                $result         = true;
                $output_value = $value;
                break;
            }
        }else if(is_array($value) || is_object($value)){
            if(is_object($value)){
                $value = (array)$value;
            }
            $result = arrayKeySearch($value, $search_key, $output_value, $occurence);
            if($result){
                break;
            }
        }
    }
    return $result;
}

Upvotes: 0

tristanbailey
tristanbailey

Reputation: 4605

So you don't you your id key for the first level, so loop through and when you find a match stop looping and break out of the foreach

$id = 0;
$needle = 63;
foreach($array as $i => $v)
{
    if ($v['no'] == $needle)
    {
        $id = $i;
        break 1;
    }
}
// do what like with any other nested parts now
print_r($array[$id]);

Then you could use that key to get the whole nested array.

Upvotes: 0

rik
rik

Reputation: 8612

foreach ($array as $i => $v) $array[$i] = $v['no'];
$key = array_search(63, $array);

Upvotes: 1

Related Questions