Echo逗号在php中分隔值

时间:2015-03-17 10:25:11

标签: php

我有一张发票表,其中3列有逗号分隔值。现在,我想详细显示每张发票的报告。 例如:

Invoice_id=10 
product=1,5,55 
category=2,44,25 
QTY= 55,2,10

因此,对于上述发票,我想用数量显示每个产品名称和类别。

2 个答案:

答案 0 :(得分:0)

如果它们的顺序正确且具有一致的相关性,则可以这样做。

例如,您可以通过','字段进行爆炸,并在for循环中创建输出,如下所示:

//you have to retrieve the data from database, the fields are strings
$product= "1,5,55"
$category= "2,44,25"
$QTY= "55,2,10"
//for each invoice:
$products = explode(',',$product);
$categories = explode(',',$category);
$QTYs = explode(',',$QTY);
for ($i = 0; $i < count($products); $i++){
    echo "Product: " . $products[$i] . ", Category: " . $categories[$i] . ", Quantity: " . $QTYs[$i] . ".<br>"; 
}

希望有所帮助

答案 1 :(得分:0)

foreach(explode(' ', 'Invoice_id=10 product=1,5,55 category=2,44,25 QTY=55,2,10') as $key => $value)
        {
            $temp[] = explode('=', $value);
        }

        foreach($temp as $key => $value)
        {
            $final[$value[0]] = explode(',', $value[1]);
        }

        echo '<pre>';
        print_r($final);

输出:

Array
(
[Invoice_id] => Array
    (
        [0] => 10
    )

[product] => Array
    (
        [0] => 1
        [1] => 5
        [2] => 55
    )

[category] => Array
    (
        [0] => 2
        [1] => 44
        [2] => 25
    )

[QTY] => Array
    (
        [0] => 55
        [1] => 2
        [2] => 10
    )

)