Jump to content

appending to an array in foreach()


smartalco

Recommended Posts

how would you append to an array using your own key names?, i want to organize the results of a sql query differently to be easier to code with and easier to understand, but im having problems converting it

foreach($locations_query as $thingy) {		$locations .= array($thingy['id'] => $thingy['name']);	}

that, for reasons i dont know just makes locations 'ArrayArrayArrayArray' etc, one 'Array' for each time the foreach loop loops, without the '.' in '.=' (using just =) it overwrites the array each time, so all im left with is the last valueany suggestions?

Link to comment
Share on other sites

The . operator is string concatenation, it doesn't work for arrays. For arrays you can either use the array_push function, or you can use bracket notation.$locations[] = array($thingy['id'] => $thingy['name']);

Link to comment
Share on other sites

that doesn't do quite what im looking for, it creates an array as such

Array ( 	[0] => Array ( 		[$thingy[id]] => $thingy[name]	)	[1] => Array (		[$thingy[id]] => $thingy[name]	))

(the values of the php variables in place of the variables themselves, i did it this way to help show what i mean)I need

Array ( [$thingy[id]] => $thingy[name]		[$thingy[id]] => $thingy[name])

since the id is being pulled from the primary field in a sql table, it will never be the same, so each time it loops through the array a new value is put in the array with the key being the id of the record the loop is on

Link to comment
Share on other sites

You can't have EXACTLY that, you know. I mean, array keys are unique.You could have

$locations[$thingy['id']] = $thingy['name'];

[edit]Ah, you figured it out[/edit]

Link to comment
Share on other sites

Your reorganizing an array from a SQL query? why not just change the SQL query? I'm assuming your query looks something like this:

SELECT * FROM your_table

Why not just do this:

SELECT id,othercolumn,morecolumns,oy FROM your_table

Also, in this case, i believe array_merge() would have done it fine. it takes 2 array's and merges them together, but i believe you could juse use the += character and that should've worked fine.

Link to comment
Share on other sites

Your reorganizing an array from a SQL query? why not just change the SQL query? I'm assuming your query looks something like this:
SELECT * FROM your_table

Why not just do this:

SELECT id,othercolumn,morecolumns,oy FROM your_table

I needed values from one field in the sql table to be the keys in the array, can't do that with a query
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...