Reputation: 599
I an trying to create an array using explode for a string.
Here is my string:
$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
And here's my complete code:
$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$d = explode(',', $string);
echo '<pre>';
var_dump($d);
and after that i got the result like this..
array(7) {
[0]=>
string(3) "a:1"
[1]=>
string(3) "b:2"
[2]=>
string(3) "c:3"
[3]=>
string(3) "d:4"
[4]=>
string(3) "e:5"
[5]=>
string(3) "f:6"
[6]=>
string(3) "g:7"
}
How can I create an array like this instead?:
array(7) {
["a"]=>
string(1) "1"
["b"]=>
string(1) "2"
["c"]=>
string(1) "3"
["d"]=>
string(1) "4"
["e"]=>
string(1) "5"
["f"]=>
string(1) "6"
["g"]=>
string(1) "7"
}
Upvotes: 2
Views: 19052
Reputation: 77094
This should work:
$arr = array();
$d = explode(',', $string);
for($d as $item){
list($key,$value) = explode(':', $item);
$arr[$key] = $value;
}
Upvotes: 6
Reputation: 31641
This is a simple solution using loops:
$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$pairs = explode(',', $string);
$a = array();
foreach ($pairs as $pair) {
list($k,$v) = explode(':', $pair);
$a[$k] = $v;
}
var_export($a);
You can also do this (in PHP >= 5.3) in a more functional manner:
$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$pairs = explode(',', $string);
$items = array_map(
function($e){
return explode(':', $e);
},
$pairs
);
$a = array_reduce(
$items,
function(&$r, $e) {
$r[$e[0]] = $e[1];
return $r;
},
array()
);
var_export($a);
Upvotes: 1
Reputation: 442
<?php
foreach($d as $k => $v)
{
$d2 = explode(':',$v);
$array[$d2[0]] = $d2[1];
}
?>
Upvotes: 6