views:

61

answers:

2

Is there any way I can avoid using array_flip to optimize performance. I am doing a select statement from database, preparing the query and executing it and storing data as an associative array in $resultCollection and than I have array op and for each element in $resultCollection am storing its outputId in op[] as evident from the code.

I have explained code and so my question is how can I achieve an similar alternative for array_flip with using array_flip as I want to improve performance.

$resultCollection = $statement->fetchAll(PDO::FETCH_ASSOC);

$op = array();

//Looping through result collection and storing unicaOfferId into op array. 
foreach ($resultCollection as $output)
{
$op[] = $output['outputId'];
}

//Here op array has key as 0, 1, 2...and value as id {which I am interested in}

//Flip op array to get offer ids as key

$op = array_flip($op);

//Doing a flip to get id as key. 

foreach ($ft as $Id => $Off)
{
    $ft[$Id]['is_set'] = isset($op[$Id]);
}
A: 

Well, since it doesn't look like you care about the value, bur rather just the O(1) lookup speed of the keys, I'd build the $op that way the first time

foreach ($resultCollection as $output)
{
  $op[$output['outputId']] = null;
}

Or you can look into in_array(), I don't know how its speed compares. (Seems like this is 0(n), so not faster)

EDIT

If you wanted to create the first time around what you were getting after array_flip(), do it this way.

$i = 0;
foreach ($resultCollection as $output)
{
  $op[$output['outputId']] = $i++;
}

But after your comments, I'm still not sure if I really "get" what you're after.

Peter Bailey
Why do you assign it to null, everytime in loop ?
Rachel
This is not am looking for !!!
Rachel
in_array has to linear search of the array O(n), using array_key_exists will allow usage of the hash O(1) time.
Kendall Hopkins
Because you say pretty clearly in the comments that it's the outputId value that you are interested in, and from this code snippet it never looks like you use the values (post-array_flip), so NULL is just a way to assign a low-memory value.But they don't have to be nulls - could be an incremented integer if you want. I'll add that to my answer.
Peter Bailey
+1  A: 

You should be able to use the key from the foreach for indexes and build the array pre-flipped like this.

    foreach ($resultCollection as $key => $output) {
        $op[ $output['outputId'] ] = $key;
    }
Kendall Hopkins