Re: array conversion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Or:

$a = array ('Cats', 'white', 'Dogs', 'black', 'Mice', 'grey', 'Camels', 'brown');
$b = ''; 				// Just in case it has some leftover value
$k = 2* (int) (count ($a)/2);	// ensure even no of terms
$i = 0; while ($i < $k)
	{ 
	$b[$a[$i++]] = $a[$i++];  // ***
	}

And this works:
$i = 0; $k = array_keys($b); 
while ($i < count($b)) { 	echo '<h5>'.$i.': '.$k[$i].' = '. $b[$k[$i++]].'</h5>'; }

0: Cats = white
1: Dogs = black
2: Mice = grey
3: Camels = brown

( *** I have always been wary of using statements like this because I was unsure when the
incrementing would occur, so I tried it.)

Clancy

On Fri, 19 Feb 2010 02:26:49 -0500, simpleshot@xxxxxxxxx (Adam Richardson) wrote:

>Or,
>
>function new_arr(array $arr)
>{
>    $count = count($arr);
>    if ($count % 2 != 0) throw new Exception('The new_arr() function
>requires an even number of elements.');
>    for ($i = 0; $i < $count; $i += 2)
>    {
>        $new_arr[$arr[$i]] = $arr[$i + 1];
>    }
>    return $new_arr;
>}
>
>$test = new_arr(array('k1', 'v1', 'k2', 'v2', 'k3', 'v3'));
>
>exit(var_dump($test));
>
>On Fri, Feb 19, 2010 at 1:19 AM, Larry Garfield <larry@xxxxxxxxxxxxxxxx>wrote:
>
>> On Thursday 18 February 2010 11:58:28 pm Paul M Foster wrote:
>> > On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:
>> > > Hi guys. How to convert an array like:
>> > >
>> > > Array
>> > > (
>> > >     [0] => key1
>> > >     [1] => value1
>> > >     [2] => key2
>> > >     [3] => value2
>> > > )
>> > >
>> > > to
>> > >
>> > >
>> > > Array
>> > > (
>> > >     [key1] => value1
>> > >     [key2] => value2
>> > > )
>> > >
>> > > Is there a built-in function to do this?
>> > > Please Cc me. :)
>> > > Thank you in advance.
>> >
>> > I don't believe so, but rolling your own should not be too hard:
>> >
>> > $a = array($key1, $value1, $key2, $value2);
>> > $b = array();
>> > $numitems = count($a);
>> >
>> > for ($i = 0; $i < $numitems; $i++) {
>> >       if ($i % 2 == 0) {
>> >               $saved_key = $a[$i];
>> >       }
>> >       elseif ($i % 2 == 1) {
>> >               $b[$saved_key] = $a[$i];
>> >       }
>> > }
>> >
>> > Code is crude and untested, but you get the idea.
>> >
>> > Paul
>>
>> This would be even shorter, I think:
>>
>> foreach ($items as $i => $value) {
>>  $temp[$i % 2][] = $value;
>> }
>> $done = array_combine($temp[0], $temp[1]);
>>
>> (Also untested, just off the cuff...)
>>
>> --Larry Garfield
>>
>> --
>> PHP General Mailing List (http://www.php.net/)
>> To unsubscribe, visit: http://www.php.net/unsub.php
>>
>>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux