6

I have an array being returned from the database that looks like so:

$data = array(201 => array('description' => blah, 'hours' => 0),
              222 => array('description' => feh, 'hours' => 0);

In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:

foreach ($data as $row => $value){
   $query = $db->query('SELECT * FROM t WHERE id=$row');
   if ($result){
      $value['hours'] = $result['hours'];
   }

It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.

Surely this is easier than my brain is perceiving it.

Here's the whole snippet:

foreach($_gspec as $key => $value){

            $sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
            $query = $db->query($sql);

            if ($query->num_rows() !== 0){

                $result = $query->row_array();
                $value['hours'] = $result['hours'];

            }
        }
1
  • What are $result and $query variables? Commented Apr 20, 2010 at 20:34

3 Answers 3

6

You want

$data[$row]['hours'] = $result['hours']

$row would be better named as $key (that is what it is!)

Some people would suggest using pointers, but I find this way makes more sense to me.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to use ampersand in front of the $value in foreach to pass it by reference like this:

foreach ($data as $row => &$value){
   $query = $db->query($sql);
   if ($result){
      $value['hours'] = $result['hours'];
   }
}

More info here: http://php.net/manual/en/control-structures.foreach.php

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

1 Comment

I accepted the other answer because that's what I went with for my own sanity, but I gave you an uptick because this works just as well.
0

Use reference ->

foreach ($data as $row => & $value) {
   $query = $db->query('SELECT * FROM t WHERE id=$row');
   // [...]
   if ($result) {
      $value['hours'] = $result['hours'];
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.