How to change a value in an array by key name

Discussion in 'PHP' started by jwitt98, Jul 26, 2011.

  1. #1
    This has been driving me nuts :confused:
    I have this array where in certain cases I need to change a value in the array from NULL to some other value. I can change the value by using the numeric key, but not by the key name. Here is the example:
    
    while($row = @mysql_fetch_array($r)){
    		echo "<tr>\n";
    		for($i=0; $i < sizeof($_SESSION['parts']['columns_selected']); ++$i){
    			$row['price'] = 1.11;
    			echo "<td>".$row[$i]."</td>\n";
    		}
    		echo "</tr>\n";
    	}
    
    PHP:
    I would think that every row would have a price of 1.11, but this does not work.
    If I change line 4 to:
    
    $row[12] = 1.11;
    
    PHP:
    it works as expected and every row displays 1.11 for price. The problem is that the number of items in the array changes depending on what the user selects, so it will not always be $row[12].
    I hope someone can help me figure this out.

    Here is some additional information:
    One row of the output of print_r(array($row)) with sensitive info removed:
    
    Array ( [0] => Array ( [0] => 4 [request_id] => 4 [1] => 12345001 [part_number] => 12345001 [2] => 4-Port Hub [part_description] => 4-Port Hub [3] => XXX [vendor] => XXX [4] => 4 [quantity] => 4 [5] => XXX [first_name] => XXX [6] => XXX [last_name] => XXX [7] => XXX [address] => XXX [8] => XXX [city] => XXX [9] => XX [state] => XX [10] => XXXXX [zip] => XXXXX [11] => AZAA-123456 [po_number] => AZAA-123456 [12] => 25.99 [price] => 25.99 [13] => 103.96 [(price * quantity)] => 103.96 [14] => Received-closed [status] => Received-closed ) )
    
    PHP:
     
    Last edited: Jul 26, 2011
    jwitt98, Jul 26, 2011 IP
  2. dthoai

    dthoai Member

    Messages:
    106
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    38
    #2
    I think your codes should be changed to:

    
    [COLOR="red"]$columns = $_SESSION['parts']['columns_selected'];[/COLOR]
    while($row = @mysql_fetch_array($r)){
            [COLOR="red"]$row['price'] = 1.11;[/COLOR]
            echo "<tr>\n";
            for($i=0; $i < sizeof([COLOR="red"]$columns[/COLOR]); ++$i){
                echo "<td>".[COLOR="red"]$row[$columns[$i]][/COLOR]."</td>\n";
            }
            echo "</tr>\n";
    }
    
    Code (markup):
     
    Last edited: Jul 26, 2011
    dthoai, Jul 26, 2011 IP
  3. jwitt98

    jwitt98 Peon

    Messages:
    145
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, but $_SESSION['parts']['columns_selected'] does not contain the data I need to fill in the table. It is only used to obtain the number of loops to run.
    I sill am having the problem with replacing the data in the array when using the key name.
     
    jwitt98, Jul 26, 2011 IP