tags:

views:

292

answers:

2

I have an multidimensional array that looks like this:

Array
(
    [0] => Array
        (
            [ClientID] => ec2173de2134fdsfg4fsdffcb4b5205
            [Name] => ABC Widgets
        )

    [1] => Array
        (
            [ClientID] => e5dfgfdg2d760f640aadfgdfgdfg47b
            [Name] => Acme Co
        )

    [2] => Array
        (
            [ClientID] => b9dfgsdfg419085c3sdgffdsgfdg313
            [Name] => 4321 Corp
        )

)

I would like to change to the following:

Array
(
  ec2173de2134fdsfg4fsdffcb4b5205 => ABC Widgets
  e5dfgfdg2d760f640aadfgdfgdfg47b => Acme Co
  b9dfgsdfg419085c3sdgffdsgfdg313 => 4321 Corp
)

What is the best way to do so? Also, would I be better off storing the array in its original format and converting to other formats as needed? Thank you for any assistance

+3  A: 
$flat = array();
foreach($multidim as $item)
    $flat[$item['ClientID']] = $item['Name'];

Whether you'd be better off storing the original form cannot be answered generally. You should store it if you need it.

chaos
Thank you for the clear and concise answer.
rickvug
A: 

It looks like you are creating a hash table with the original data. Hash tables are very fast for accessing and inserting single data elements. However, you can't run queries against the data contained in the records--you can only retrieve based on the unique key or insert based on a generated key.

You might use the original format with all its fields as the "back-end" and generate a hash table like the one you demonstrated. The draw-back is that every time this table is generated, it costs CPU cycles.

If you throw this data into a database, the DB engine will handle creating regular data tables (like your first one) and hash tables (like your second) as needed for the particular query that you are using. You can also force it to create hash tables based on a certain database column.

Nolte Burke
The use case is that I'm working with the Campaign Monitor (email software) API. The hashes are the API keys that belong to a client.
rickvug
Well, the advice is still valid for questions regarding how and why you should store things in a particular way. Best of luck!
Nolte Burke