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.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.