Reputation: 3548
I have php var with multiple string values and numbers,
$string = 'Simple 12, Complex 16';
i explode this to an array, but i need to explode this string to be like below array.
Array(
[0] => Array(
[Simple] => 12,
[Complex] => 16
)
)
what is the perfect way to do this in php?
Upvotes: 1
Views: 116
Reputation: 1037
preg_match_all('/(\w+)\s*(\d+)/', $string, $matc);
$output = array_combine($match[1], $match[2]);
Upvotes: 0
Reputation: 391
The reply from user "Ø Hanky Panky Ø", have an error:
Here:
$result[0][$type]=$count;
Correctly is:
$result[][$type]=$count;
Upvotes: 0
Reputation: 2187
Do like this, if you want to get out put like this.
<?PHP
$string = 'Simple 12, Complex 16';
$my_arr1 = explode(',',$string);
foreach ($my_arr1 as $value) {
$value=trim($value);
$my_arr2 = explode(' ',$value);
$final_array[$my_arr2[0]]=$my_arr2[1];
}
print_r($final_array);
OUTPUT
Array
(
[Simple] => 12
[Complex] => 16
)
Upvotes: 1
Reputation: 94101
Here's a quick way:
preg_match_all('/(\w+)\s*(\d+)/', $str, $matches);
$result = array_combine($matches[1], $matches[2]);
Upvotes: 2
Reputation: 33
<?php
preg_match_all("/[A-Za-z]+/","Simple 12, Complex 16",$keys);
preg_match_all("/[0-9]{2}/","Simple 12, Complex 16",$vals);
$a = array_combine($keys[0],$vals[0]);
print_r($a);
try it out
Upvotes: 0
Reputation: 46900
<?php
$string = 'Simple 12, Complex 16';
$values=explode(",",$string);
$result=array();
foreach($values as $value)
{
$value=trim($value);
list($type,$count)=explode(" ",$value);
$result[0][$type]=$count;
}
print_r($result);
?>
Output
Array
(
[0] => Array
(
[Simple] => 12
[Complex] => 16
)
)
Upvotes: 2