将字符串分解为多级数组
我有一个问题,我需要将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);
但我不知道如何将其转换成我需要的是一个多层次的数组。
如果变量是一致的,并且字段将永远是那些6:
$productList = array_chunk(explode(':', $productsOrdered), 6);
虽然这种格式化的数据简直是一场噩梦,如果你有控制它,你应该考虑一个正确的序列化方法[例如JSON。
对于JSON建议+1。 – Styphon
非常感谢。很抱歉,支付网关Sagepay使用这种格式化数据的方法。 –
您可以使用array_chunk
:
array_chunk(explode(":", rtrim($productsOrdered, ":")), 6);
可能希望使用'array_filter()'从列表中删除空的数组元素(如果这是一个要求)。 –
感谢这工作正是我需要它。 –
变化,你是这样的获取和使用爆炸两次字符串: -
$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);
}
谢谢但上面提到了一个更好的解决方案。 –
不可能的。 explode()只能返回一个数组。如果你想要多维数组,你将不得不在循环中运行多个爆炸。 –
是已知的子数组中的项目数量? – EGN
如果这些只是相同的字符串,为什么不计算它们有多少,就像substr_count($ productsOrdered,'name:quantity:priceWithoutVat:vatAmount:priceWithVat:lineTotal'); 只需创建有序数组? –