user2426701
user2426701

Reputation:

Adding elements to an associative array during a loop

I have this loop:

foreach ($tables as $table => $queries) {
                    foreach ($queries as $query) {
                        $insert = array($query['column'] => $query['value']);
                    }

The $insert associative array should be incremented of new elements each loop, so that the logical result woud be:

 $insert = array($query['column'] => $query['value'], $query['column'] => $query['value'] ...etc);

I tried using $insert[] and $insert .= and $insert += but none of these give the expected result

Thanks for any help

Upvotes: 1

Views: 2302

Answers (4)

Pez
Pez

Reputation: 31

$insert = array();

foreach ($tables as $table => $queries) 
{

    foreach ($queries as $query) 
    {
            $insert[$query['column']] = $query['value'];      
    }

}

Upvotes: 0

Marc B
Marc B

Reputation: 360602

Once the array's been defined, you have to use

$insert[$query['column']] = $query['value']; // sample #1

to specify a new key/value pair within the $insert array.

If you use

$insert[] = array(...); // sample #2

you'll just be inserting a new child array that contains a single key/value pair.

e.g. $insert before

$insert = array(
   'foo' => 'bar'
);

$insert after sample #1

$insert = array(
    'foo' => 'bar',
    'baz' => 'qux'
);

$insert after sample #2:

$insert = array(
   'foo' => 'bar'
   0 => array(
        'baz' => 'qux'
   )
);

Upvotes: 1

Harshveer Singh
Harshveer Singh

Reputation: 4187

To insert in array use:

$insert[] = array($query['column'] => $query['value']);

Upvotes: 2

Zevi Sternlicht
Zevi Sternlicht

Reputation: 5399

You are looking for this

$insert[] = 

Upvotes: 5

Related Questions