2014-05-21 25 views
0

我有一個問題,我需要將explode(":",$productsOrdered)轉換爲多級數組。將字符串分解爲多級數組

我需要這樣的:

$productsOrdered = "name:quantity:priceWithoutVat:vatAmount:priceWithVat:lineTotal:name:quantity:priceWithoutVat:vatAmount:priceWithVat:lineTotal:name:quantity:priceWithoutVat:vatAmount:priceWithVat:lineTotal:";

變成這樣:

$productList = array(
    array(name,quantity,priceWithoutVat,vatAmount,priceWithVat,lineTotal), 
    array(name,quantity,priceWithoutVat,vatAmount,priceWithVat,lineTotal), 
    array(name,quantity,priceWithoutVat,vatAmount,priceWithVat,lineTotal), 
); 

但我需要它的工作無論多少產品是如何在$productsOrdered變量。 我用:

$product = explode(":",$product); 

但我不知道如何將其轉換成我需要的是一個多層次的數組。

+3

不可能的。 explode()只能返回一個數組。如果你想要多維數組,你將不得不在循環中運行多個爆炸。 –

+0

是已知的子數組中的項目數量? – EGN

+0

如果這些只是相同的字符串,爲什麼不計算它們有多少,就像substr_count($ productsOrdered,'name:quantity:priceWithoutVat:vatAmount:priceWithVat:lineTotal'); 只需創建有序數組? –

回答

1

如果變量是一致的,並且字段將永遠是那些6:

$productList = array_chunk(explode(':', $productsOrdered), 6); 

雖然這種格式化的數據簡直是一場噩夢,如果你有控制它,你應該考慮一個正確的序列化方法[例如JSON。

+1

對於JSON建議+1。 – Styphon

+0

非常感謝。很抱歉,支付網關Sagepay使用這種格式化數據的方法。 –

3

您可以使用array_chunk

array_chunk(explode(":", rtrim($productsOrdered, ":")), 6); 
+1

可能希望使用'array_filter()'從列表中刪除空的數組元素(如果這是一個要求)。 –

+0

感謝這工作正是我需要它。 –

0

變化,你是這樣的獲取和使用爆炸兩次字符串: -

$productsOrdered = "name:quantity:priceWithoutVat:vatAmount: priceWithVat: lineTotal: name; quantity:priceWithoutVat: vatAmount:priceWithVat:lineTotal;name:quantity : priceWithoutVat: vatAmount : priceWithVat:lineTotal;"; 

$temp=explode(";",$productsOrdered); 
$temp1=array(); 
foreach($temp as $k=>$v) 
{ 
    $temp[]=explode(":",$v); 
} 
+0

謝謝但上面提到了一個更好的解決方案。 –