1

I need to convert a string from this:

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

to an array like this:

$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 tried to use explode() to convert the string to an array but it does not work as needed.

mickmackusa
49k13 gold badges97 silver badges163 bronze badges
asked Aug 20, 2010 at 16:58
4
  • 1
    Please post the code you have used. Commented Aug 20, 2010 at 17:02
  • $arr = explode(", ", $yourString) must work, post your code please... Commented Aug 20, 2010 at 17:04
  • php.net/manual/en/function.preg-split.php Commented Aug 20, 2010 at 17:06
  • Do you control the generation of the CSV string? If so, using a different delimiter (like ";") between each set would make parsing it alot easier. ie "name1", "b", "2"; "name2", "c", "3"; "name3", "b", "2"; ... Commented Aug 20, 2010 at 17:25

3 Answers 3

3
$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
 )
)
answered Aug 20, 2010 at 17:12

1 Comment

could have edited your deleted answer as well
2

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 ) );
answered Aug 20, 2010 at 17:11

Comments

0

Parse the csv string containing quoted values, then split that flat array into 3-element chunks, then forge associative rows using hardcoded keys.

Code: (Demo)

$text = <<<TEXT
"name1", "b", "2", "name2", "c", "3", "name3", "b", "2"
TEXT;
var_export(
 array_map(
 fn($chunk) => array_combine(['name', 'char', 'qnt'], $chunk),
 array_chunk(str_getcsv($text), 3)
 )
);
answered Jul 21, 2024 at 0:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.