Jump to content


Photo

[solved] Array composition


  • Please log in to reply
4 replies to this topic

#1 448191

448191
  • Staff Alumni
  • Advanced Member
  • 3,545 posts
  • LocationNetherlands

Posted 14 September 2006 - 11:28 PM

I might be overlooking something obvious, but I don't see it right now..

I have a numeric array from which I want to compose a new associative array, with every first value as an index, the second as the value.

#2 448191

448191
  • Staff Alumni
  • Advanced Member
  • 3,545 posts
  • LocationNetherlands

Posted 14 September 2006 - 11:42 PM

LOL, never mind...

array_combine




#3 448191

448191
  • Staff Alumni
  • Advanced Member
  • 3,545 posts
  • LocationNetherlands

Posted 15 September 2006 - 12:06 AM

Hmmm... It's still a bit too bulky I feel:

<?php
function is_odd($var)
{
   return($var & 1);
}
$arr = array('key1','value1','key2','value2');
$keys = array_flip(array_filter(array_flip($arr), 'is_odd'));
$values = array_diff($arr,$keys);
$arr = array_combine($keys,$values);
?>



#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 15 September 2006 - 12:31 AM

<?php
$res = array();
$arr = array('key1','value1','key2','value2');
$arr2 = array_chunk($arr,2);
foreach ($arr2 as $a) {$res[$a[0]] = $a[1];}

?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#5 448191

448191
  • Staff Alumni
  • Advanced Member
  • 3,545 posts
  • LocationNetherlands

Posted 15 September 2006 - 12:45 AM

Thanks!  :)

End result:
<?php
function array_compose($arr){
	$arr2 = array_chunk($arr,2);
	foreach($arr2 as $a){
		$res[$a[0]] = next($a);
	}
	return $res;
}
$arr = array('key1','value1','key2','value2','emptyindex');
print_r(array_compose($arr));
?>

Outputs:

Array
(
    [key1] => value1
    [key2] => value2
    [emptyindex] =>
)






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users