Jump to content

[SOLVED] How to add values to an array that is inside of other array?


JeditL

Recommended Posts

Hi

 

I got an array like this:

 

$array[$i][$j]=array('first'=>'one','second'=>'two','third'=>null);

 

and I would like to add value to the field third later in a loop. I came up with this idea:

 

$x=0;
for($i=0;$i<$numrows;$i++)  {
        for($j=0;$j<$numfields;$j++)  {
                foreach($array[$i][$j] as $field)  {
                        $x++;
                        if($x==3)  {
                                $row='three';
                                $x=0;
                        }
                }
       }
}

 

But sure there must be easier way, right? The length of my code for the simple looking task feels just ridiculously long and complicated  ::). I hope you can help to fix it.

 

Thanks in advance.

Can you try array_push() function in php  ?

 

Thanks for the reply.

 

After googling for a while I found out how push_array() works and it didn't seem to be possible to add associative key to the field pushed but instead I found this solution:

 

$array = array('animal'=>'dog', 'name'=>'Offenbach', 'owner'=>'Mr Smith');
$array = array_push_assoc($array, 'food', 'postmans leg');

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
}

 

Link: http://www.phpro.org/examples/Array-Push-Assoc.html

 

Eh.. Simple solution  :). Problem solved!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.