开发者

Adding to a multidimensional array in PHP

开发者 https://www.devze.com 2022-12-27 08:42 出处:网络
I have an array being returned from the database that looks like so: $data = array(201 => array(\'description\' => blah, \'hours\' => 0),

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:

forea开发者_开发技巧ch($_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'];

            }
        }


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.


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.


Use reference ->

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

精彩评论

暂无评论...
验证码 换一张
取 消