vote up 0 vote down star
1

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"

flag

Just out of curiosity, why do you want to do it without loops? – Anti Veeranna Dec 22 at 18:41

7 Answers

vote up 3 vote down

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

link|flag
Unless of course the multidimensional arrays are always of the same size, but thats not usually a good assumption.... – ghills Dec 22 at 18:26
vote up 3 vote down

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

link|flag
vote up 1 vote down
preg_match_all("~([^|,]+),([^|,]+)~", $str, $m);
$result = array_combine($m[1], $m[2]);

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

link|flag
vote up 0 vote down

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

link|flag
vote up 0 vote down

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,
);
link|flag
vote up 0 vote down

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);
link|flag
vote up -2 vote down

A small loop would be best.

$array1 = split('|',$data);
$final=array();
$foreach($array1 as $arraypart) {
$part = split(',',$arraypart);
$final[$part[0]] = $part[1];
}
link|flag
The question stipulated "without loops", and your code is broken. – meagar Dec 22 at 18:37

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.