Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to a multidimensional array in PHP

Tags:

arrays

php

mysql

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'];

            }
        }
like image 538
b. e. hollenbeck Avatar asked Apr 20 '10 20:04

b. e. hollenbeck


Video Answer


2 Answers

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.

like image 72
Adam Hopkinson Avatar answered Oct 05 '22 22:10

Adam Hopkinson


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.

like image 30
Janci Avatar answered Oct 05 '22 22:10

Janci