tags:

views:

60

answers:

2

I need to convert string

"name1", "b", "2", "name2", "c", "3", "name3", "b", "2", ....

to an array like

$arr[0]['name'] = "name1";
$arr[0]['char'] = "b";
$arr[0]['qnt'] = "2";

$arr[1]['name'] = "name2";
$arr[1]['char'] = "c";
$arr[1]['qnt'] = "3";

$arr[2]['name'] = "name3";
$arr[2]['char'] = "b";
$arr[2]['qnt'] = "2";

I used explode to extract an string to array but it not work

Any idea?

+2  A: 

If you do not care about the array keys being numeric, you can do:

$string = 'name1, b, 2, name2, c, 3, name3, b, 2';
print_r( array_chunk( explode(',', $string), 3 ) );
Gordon
+3  A: 
$input = '"name1", "b", "2", "name2", "c", "3", "name3", "b", "2"';
$input = str_replace('"', '', $input);
$input = explode(', ', $input);

$output = array();
$i = 0;
while ($i < count($input)) {
    $output[] = array(
        'name' => $input[$i++],
        'char' => $input[$i++],
        'qnt' => $input[$i++]
    );
}

print_r($output);

Output:

Array
(
    [0] => Array
        (
            [name] => name1
            [char] => b
            [qnt] => 2
        )

    [1] => Array
        (
            [name] => name2
            [char] => c
            [qnt] => 3
        )

    [2] => Array
        (
            [name] => name3
            [char] => b
            [qnt] => 2
        )

)
Edward Mazur
[could have edited](http://stackoverflow.com/posts/3533174/edit) your deleted answer as well
Gordon