scorpio1441
scorpio1441

Reputation: 3088

Search key by value in multi dimensional array

Using PHP's website as a reference I'm trying to search for a key of the known value in associative array:

http://php.net/manual/en/function.array-search.php

The following code always returns 1, but suppose to return 120:

$location_key = array_search(1, array_column($locations, 'main'));

print_r($locations):

Array
(
    [120] => Array
        (
            [clientid] => 122103
            [name] => HQ
            [address] => 2013 BENSON GARDEN BLVD
            [address2] => 
            [city] => OMAHA
            [state] => NE
            [zip] => 68134
            [country] => UNITED STATES
            [lat] => 00.000
            [lng] => -0.0000
            [taxrate] => 0
            [main] => 1
            [active] => 1
            [contactid] => 14
        )

    [122] => Array
        (
            [clientid] => 122103
            [name] => Branch
            [address] => 515E E 72ND ST
            [address2] => 
            [city] => NEW YORK
            [state] => NY
            [zip] => 10021
            [country] => UNITED STATES
            [lat] => 40.766705
            [lng] => -73.952965
            [taxrate] => 0
            [main] => 0
            [active] => 1
            [contactid] => 0
        )

)

Not sure why PHP's website is referencing the highest up voted "User Contributed Note" which doesn't work.

Upvotes: 0

Views: 75

Answers (1)

Rizier123
Rizier123

Reputation: 59681

This is because array_column() doesn't keep your keys. So you first need to array_combine() the keys with the array from array_column(), e.g.

$location_key = array_search(1, array_combine(array_keys($locations), array_column($locations, 'main')));

Upvotes: 1

Related Questions