Re: [PHP] array conversion

[email protected] (Paul M Foster)
Newsgroups php.general
Message-ID <[email protected]>
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

-- 
Paul M. Foster
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.