Adding to a multidimensional array in PHP

I have an array returned from a database that looks like this:

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

In the next bit of code, I use foreach and check the key for another table. If the following query returns data, I want to update the "hours" value in this key array with the new hours value:

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

Everything is fine, except that I tried almost every combination of declarations for the foreach loop, but I keep getting the error that $value['hours'] is an invalid link. I tried declaring $value[] ... but this does not work either. I do not need to go through $value , so another foreach not needed.

Of course, this is easier than my brain perceives 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']; } } 
+6
arrays php mysql
source share
3 answers

Do you want to

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

$row will be better named $key (that's what it is!)

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

+6
source share

You need to use the ampersand before the $ value in foreach to pass it by reference:

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

Further information here: http://php.net/manual/en/control-structures.foreach.php

Starting with PHP 5, you can easily change the array elements preceding $ value with &. This will assign the link instead of copying the value.

+3
source share

Use reference β†’

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

All Articles