reducing 2D array to single array of select key => value? |
[eluser]gscharlemann[/eluser]
Is there an easy way to create a new array from a 2D array? Retrieving "groups" from a database, I get the following: Code: Array I want to put the values of id and group in an array as key => value to use in the form_dropdown function of the Form Helper. I can setup a new array and iterate through the the groups array adding the key=>value pair to the new array, but thought there might be something fancier out there I'm not aware of. Thanks for the help.
[eluser]mattpointblank[/eluser]
I'd be interested to know this too. I find myself adding foreach loops at the end of database functions that reformat my arrays like this for this exact purpose.
[eluser]danmontgomery[/eluser]
Plenty of different ways to do this. http://www.google.com/search?q=php+flatten+array
[eluser]mattpointblank[/eluser]
Most of those results don't do what we need (I think). Take this example: Code: $articles = array( The array I want out of this would be: Code: $articles = array(34 => 'test', 654 => 'hello', 265 => 'world'); It's quite custom code - any kind of function would need to know the field names to group with.
[eluser]mattpointblank[/eluser]
Wrote a quick function to do this, after reflecting on a method. It expects you to pass it a CI-style multidimensional array, plus the name of your database's primary key column (defaults to 'id'). It also assumes you've only got two keys in your array as in the examples above, so it's only really suited to specific queries for those dropdown menus. Code: function array_flatten($array, $name_of_key = 'id')
[eluser]n0xie[/eluser]
Code: //If you extend from a MY_Model where you have the table name stored you can do add this to your MY_Model:
[eluser]gscharlemann[/eluser]
Thanks for the options. I think the latter option (My_Model extension) works better as I have more than 2 values in the array... although it would be nice to do this outside of querying the database. Maybe there is an option to extend the flatten_array() function mattpointblank wrote and specify the key and value... hmmm. Thinking it through: Code: Array Code: Array( 1 => "admin", 2 => "members")
[eluser]mattpointblank[/eluser]
It's trivial to extend: Code: function array_flatten($array, $name_of_key = 'id', $name_of_value)
|
Welcome Guest, Not a member yet? Register Sign In |