Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to search through this php array of associative arrays

I have the following php array;

array(
    (int) 0 => array(
        'records' => array(
            'id' => '25',
            'parent_id' => '1',
            'address' => '896167',
        )
    ),
    (int) 1 => array(
        'records' => array(
            'id' => '26',
            'parent_id' => '2',
            'address' => '890812',
        )
    ),
    (int) 2 => array(
        'records' => array(
            'id' => '28',
            'parent_id' => '16',
            'address' => '8A3813',
        )
    ),
    (int) 3 => array(
        'records' => array(
            'id' => '29',
            'parent_id' => '17',
            'address' => '8A3914',
        )
    )
)

Suppose I want to find which key has 'id' => '29', what is a fast way to search through this array and return the correct key? In this case, the correct answer is 3.

EDIT: Would anyone advise whether using foreach to loop through the array or using array_search would be faster? Or are they about the same speed?

like image 405
guagay_wk Avatar asked Oct 23 '25 05:10

guagay_wk


1 Answers

If you will be doing many such searches, it is best to create a reverse lookup array.

That is, you do the slow linear work one time, after that, it is a quick hash (associative array) lookup.

One time:

$id2index = array();
foreach ($data as $index => $value) {
    $id2index[$value->id] = $index;
}

Used many times - find index for given id:

$index = $id2index[$id];
like image 142
ToolmakerSteve Avatar answered Oct 24 '25 18:10

ToolmakerSteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!