开发者

How to parse key/value chain into associative array in PHP?

开发者 https://www.devze.com 2023-02-10 19:16 出处:网络
I开发者_StackOverflow have a string that looks like: key1/value1/key2/value2/ and so on I did an explode(\'/\',trim($mystring,\'/\')) on that

I开发者_StackOverflow have a string that looks like: key1/value1/key2/value2/ and so on

I did an explode('/',trim($mystring,'/')) on that

Now I want to haven an associative array like:

array(
 'key1' => 'value1',
 'key2' => 'value2',
  ...
);

of course i can do it with an for loop where i always read two entries and push them into a target array, but isnt there something more efficient and elegant? a one liner with some some php core function similar to ·list()· or something?


A method using array_walk() with a callback function:

function buildNewArray($value, $key, &$newArray) {
    (($key % 2) == 0) ? $newArray[$value] = '' : $newArray[end(array_keys($newArray))] = $value;
}

$myString = 'key1/value1/key2/value2/';
$myArray = explode('/',trim($myString,'/'));

$newArray = array();
array_walk($myArray, 'buildNewArray', &$newArray);

var_dump($newArray);


If the format is not changin (i mean it is allways Key1/value1/key2/value2) it should be easy.

After the explode you have this:

$arr = Array('key1','value1','key2','value2')

so you now can do:

$new_arr = array();
$i = 0;    
for($i=0;$i<count($arr);$i+=2)
{
   $new_arr[$arr[i]] = $arr[$i+1];
}

at the end of the loop you will have:

$new_arr = array("key1"=>"value1","key2"=>"value2") 

KISS :)

HTH!


One can always make yourself a one liner.

This is called User-defined functions

No need to devise something ugly-but-one-liner-at-any-cost.
Make your own function and you will get much shorter, cleaner and way more reliable result.
A function, which will not only do elementary string operations but also do something more intelligent, like parameter validation.

0

精彩评论

暂无评论...
验证码 换一张
取 消