2012-05-10 104 views
1

我有一個字符串,我想單獨製作一個多維數組。該字符串看起來是這樣的:如何從這個字符串創建多維PHP數組?

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

不幸的是,我有過的字符串是如何放在一起,這就是爲什麼我試圖讓這個數組沒有控制權。

我的目標是做一個這樣的數組:

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

所以,這裏是我做了什麼:

$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; 

    } 

} 

我顯然與此...任何建議失去了什麼?

+0

這是否總是字符串的格式?哪些部分可能會發生變化? –

回答

0

你大部分都在那裏。只是

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

} 
0

你靠近,這是我會怎麼做:

$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); 

使用list這裏是偉大的:)別注意,你需要在explode額外的計數限否則你可能會失去,如果有數據更多:

0
$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; 
0
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,"; 
$num_attr = 3; 

$item = array(); 
$i=$x=0; 
foreach(explode(',', trim($string,',')) as $attr) 
{ 
    list($key, $value) = explode(':', $attr); 
    $item[$x+=($i%$num_attr==0?1:0)][$key] = $value; 
    $i++; 
} 

設置$ num_attr項的數量字符串中的屬性替換你的內心foreach(這將允許在未來的調整,如果他們放大/縮小)。 foreach內部的修剪會刪除像最後一個逗號這樣的「空」數據(如果有人出現,它也會刪除空的第一個逗號)。看起來很瘋狂的$ item [$ x + =($ i%$ num_attr == 0?1:0)]取的是計數器的模數/屬性的數量,當它爲0時意味着我們在新的產品線上我們將1添加到填充項目號索引的x,如果模數返回一個數字,那麼我們知道我們在同一個產品上,所以我們添加0,這不會改變項目索引,因此該屬性會添加到同一個項目中。