retrieving data into a two-dimensional array

Discussion in 'PHP' started by bonecone, Mar 30, 2012.

  1. #1
    I want to retrieve my data into a two-dimensional array that I can navigate through with a foreach loop, and be able to add new fields to the array afterwords.

    For example
    
    foreach($query_results as $qr)
    {
         $qr->brand_new_field = retrieve_other_data($qr->first_field, $qr->second_field);
    }
    
    Code (markup):
    I`m going around in circles with this but I can`t quite seem to get it right. Any suggestions?
     
    bonecone, Mar 30, 2012 IP
  2. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #2
    foreach($query_results as &$qr) {
          $qr->brand_new_field = retrieve_other_data($qr->first_field, $qr->second_field);
    }
    PHP:
    Pass by reference, not value ;)
     
    Alex Roxon, Mar 30, 2012 IP
  3. samyak

    samyak Active Member

    Messages:
    280
    Likes Received:
    7
    Best Answers:
    4
    Trophy Points:
    90
    #3
    I dont think you have to pass it by reference instead of value. More codes might help diagnose the problem.
     
    samyak, Apr 1, 2012 IP
  4. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #4
    Au contraire. Passing by reference instead of by value will fix his problem. Read through PHP's official documentation on the subject: http://au.php.net/manual/en/control-structures.foreach.php

    The problem is, when you simply use foreach to loop through, you're creating a temporary copy of the array value. In that sense, when you modify that value, you're only modifying the copy, and not the original ;) Passing by reference allows you to loop through and make changes to the original array value.
     
    Alex Roxon, Apr 1, 2012 IP