0

I will be reusing a Drupal db_query result set unpacking function many, many times in my code for a variety of different queries - I am using O-O and as such I want to reuse it and be as 'DRY' as possible.

Therefore I have tried to strip it down to the most generic functions so that as long as the $columns supplied match the columns used in the query and similarly in the $resultset, I can loop and assign values to keys, as is shown, and return a $rows[].

I've not yet come across the issue of trying to use a variable's value as a variable name (the $key), if it's just something I should avoid entirely, please say.

foreach($this->resultSet as $aRecord) {

    $c = 0;

    while (isset($this->columns[$c])) {

        $value =  $this->columns[$c];
        $rows[$i] = array(
            $key[$this->columns[$c]] => $aRecord->$value,
        );

        $c++;
    }

    $i++;
}

I've read through the following and am beginning to think this is just knowledge I'm missing in my PHP experience so far.

Can I use a generated variable name in PHP?

PHP use function return value as array

https://wiki.php.net/rfc/functionarraydereferencing

Community
  • 1
  • 1
ja_him
  • 417
  • 1
  • 4
  • 20
  • `$key = 'abc'; $abc = 'hello'; echo $$key;` prints 'hello'. Was that the question? – Ranty Dec 18 '12 at 10:48
  • 1
    Why don't you just use `$this->resultSet->fetchAssoc()` which gives you an assoc array with key-value of column name => value – MrCode Dec 18 '12 at 10:50
  • It's really hard to understand what your actual problem is (e.g., how is function-array-dereferencing related?) - could you please elaborate a bit on that? – Niko Dec 18 '12 at 10:54
  • function-array-dereferencing is more related by things I believe I have rejected as a solution (and/or just don't understand correctly). – ja_him Dec 18 '12 at 11:06
  • I want to create an array of rows with key/value pairs on columns and their values. I want to be able to do this by creating a class that takes in an array of columns so that I can use the name (value) of the column as a key's name (variable name), but as I've never thought of trying to use a value of something as a key I'm not sure if I'm getting it all wrong. Thanks for your responses so far. – ja_him Dec 18 '12 at 11:10
  • Also, I will look into using fetchAssoc() now, thanks – ja_him Dec 18 '12 at 11:10

1 Answers1

0

It felt wrong, and someone once told me that if you have to start writing complex functions in PHP you've probably missed an available function PHP already offers.. so true... thanks to (at the time of writing...) 'MrCode' for this suggestion.

    $this->sql = "SELECT foo, bar FROM foobar";
    $this->result = db_query($this->sql);

    if ($this->result->rowCount() > 0) {

        while ($row = $this->result->fetchAssoc()) {

            $this->resultArray[] = $row; 
        }
    }
ja_him
  • 417
  • 1
  • 4
  • 20