PHP拆分两次

时间:2012-07-14 22:34:46

标签: php mysql

我有一个带有交易字段的数据库,这显示了我网站上的产品。我正在尝试开发一个管理界面,在那里我可以看到带来的产品。

字符串看起来像这样 37,2:27,1:5,3:94,10:49,15:

这基本上意味着客户订购的产品ID号为37,数量为2.包括在他们的交易中的是产品ID 27,数量为1,依此类推。

product_id,ordered_quantity:nextproduct_id,next_orderedquantity

为了显示这些信息,我需要将其分解。我尝试过php爆炸,但遇到了一些麻烦。因此,我们需要将产品拆分为冒号:,将qty和id拆分为comma。字符串可以是一个或多个产品。

有人有任何建议吗?

2 个答案:

答案 0 :(得分:2)

$ids = '37,2:27,1:5,3:94,10:49,15';
$products = explode(':', $ids);
$productAndQuantity = array();
foreach ($products as $product) {
    $exploded = explode(',', $product);
    $productAndQuantity[$exploded[0]] = $exploded[1];
}

您获得了产品ID - 数量数组。

这种存储数据的方式不可扩展且容易出错。为什么不使用包含以下字段的表:userId,productId,quantity?

答案 1 :(得分:-1)

这是我扔在一起的东西 -

$str = '37,2:27,1:5,3:94,10:49,15:';

$a = explode(':',$str); // split by colon ":"

$data = array(); 
foreach ($a as $product) {  // iterate over each product
    $item = explode(',',$product); // split product and quanitity
    $data[$item[0]] = array(  // use product_id [0] as array key
      'product_id'=>$item[0],
      'quantity'=>$item[1]
    );
}

// in this example there is a trailing colon - this removes it.    
array_pop($data);

print_r($data);

Array
(
    [37] => Array
        (
            [product_id] => 37
            [quantity] => 2
        )

    [27] => Array
        (
            [product_id] => 27
            [quantity] => 1
        )

    [5] => Array
        (
            [product_id] => 5
            [quantity] => 3
        )
    ...
)
相关问题