views:

242

answers:

7

How do I split a string into a multidimensional array in PHP without loops?

My string is in the format "A,5|B,3|C,8"

+3  A: 

Without loops at all? Can't be done. Without you having to write the loop? Explode or one of the regex "split" methods.

Azeem.Butt
Unless of course the multidimensional arrays are always of the same size, but thats not usually a good assumption....
ghills
A: 

You can use a combination of map and explode, but you're not really avoiding a loop, you're just not using for/while statements.

http://php.net/manual/en/function.array-map.php

Tim
A: 

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,
);
JP
+4  A: 

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...

Pascal MARTIN
+1  A: 
preg_match_all("~([^|,]+),([^|,]+)~", $str, $m);
$result = array_combine($m[1], $m[2]);

this returns an array like array('A' => 5, 'B' => 3 etc

stereofrog
A: 

A small loop would be best.

$array1 = split('|',$data);
$final=array();
$foreach($array1 as $arraypart) {
$part = split(',',$arraypart);
$final[$part[0]] = $part[1];
}
MindStalker
The question stipulated "without loops", and your code is broken.
meagar
A: 

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);
Alf Eaton