I have a string I would like to separate and make a multidimensional array out of. The string looks like this:

$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";

Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.

My goal is to make an array like this:

$item[1]['color'] // = blue
$item[2]['material'] // = silk

So, here's what I've done:

$item = array();

$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item  

foreach ($eachitem as $values) {

    $i++; // Again, very messy
    $eachvalue = explode(",",$values);
    array_pop($eachvalue); // get rid of the last comma before each new item

    foreach ($eachvalue as $key => $value) {

        $item[$i][$key] = $value;

    }

}

I'm obviously lost with this... any suggestions?

link|improve this question

Is that always the format the string will be? What are the parts that are subject to changes? – Sam 24 mins ago
feedback

3 Answers

You're close, this is how I would do it:

$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
    $subitems = array();
    $pairs = explode(",", $string);
    foreach ($pairs as $pair) {
        list($key, $value) = explode(":", $pair, 2);
        $subitems[$key] = $value;
    }
    $items[] = $subitems;
}
var_dump($items);

Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.

link|improve this answer
feedback
$array = array();
$string = explode(',', $string);
foreach($string as $part):
   $part = trim($part);
   if(strlen($part) < 3) continue;
   $part = explode(':', $part);
   $array[$part[0]] = $part[1];
endforeach;
link|improve this answer
feedback

You're mostly there. Just replace your inner foreach with

foreach ($eachvalue as $value) {
    $properties = explode(':', $value);
    $item[$i][$properties[0]] = $properties[1];

}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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