Jump to content

Associative Array Values as keys for Associate Array


ThomasNorth

Recommended Posts

Hi there,

 

Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway)

 

My question is: is there a short-hand way to use a value from an associative array as the key in another associative array?

 

So for example, given this array:

 

$the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....);

 

then this kind of foreach loop doesn't work

 

$new_data = array();
foreach($the_array as $element){
$new_data[$element['name']] = $element['value']; 
}

 

Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it?

 

Cheers,

 

PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails.

 

Hiya Silkfire,

 

Thanks for getting back to me.

 

Just to clarify if anyone else happens to have a similar question, array_combine was applied in this context by doing:

 

$new_element = array_combine(array_keys($item), $item);

 

Cheers Silkfire!

 

D.

 

 

Archived

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

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