How do I split a string into a two dimensional array without loops?
My string is in the format "A,5|B,3|C,8"
Without you actually doing the looping part, something based on array_map + explode should do the trick ; for instance, considering you are using PHP 5.3 :
$str = "A,5|B,3|C,8";
$a = array_map(
function ($substr) {
return explode(',', $substr);
},
explode('|', $str)
);
var_dump($a);
Will get you :
array
0 =>
array
0 => string 'A' (length=1)
1 => string '5' (length=1)
1 =>
array
0 => string 'B' (length=1)
1 => string '3' (length=1)
2 =>
array
0 => string 'C' (length=1)
1 => string '8' (length=1)
Of course, this portion of code could be re-written to not use a lambda-function, and work with PHP < 5.3 -- but not as fun ^^
Still, I presume array_map will loop over each element of the array returned by explode... So, even if the loop is not in your code, there will still be one...
Without loops at all? Can't be done. Without you having to write the loop? Explode or one of the regex "split" methods.
Depending on whether array_walk() counts as a loop...
<?php
class Splitter {
function __construct($text){
$this->items = array();
array_walk(explode('|', $text), array($this, 'split'));
}
function split($input){
$this->items[] = explode(',', $input);
}
}
$s = new Splitter("A,5|B,3|C,8");
print_r($s->items);
So long as you know how many items will be in each row, you can declare one or more capture groups in a single lookahead.
This is "not a loop", or at least it is not a loop like foreach() or array_map(). Demo
$str = "A,5|B,3|C,8";
preg_match_all(
'/[^,|]+(?=,([^|]+))/',
$str,
$m,
PREG_SET_ORDER
);
var_export($m);
Output:
array (
0 =>
array (
0 => 'A',
1 => '5',
),
1 =>
array (
0 => 'B',
1 => '3',
),
2 =>
array (
0 => 'C',
1 => '8',
),
)
If your data is huge this could get heavy but here's one solution:
<?php
$data = "A,5|B,3|C,8";
$search = array("|",",");
$replace = array("&","=");
$array = parse_str(str_replace($search, $replace, $data));
?>
Would result into something like this:
$array = array(
A => 5,
B => 3,
C => 8,
);