同じ形式を使用できますが、ID 列を追加すると、次のようになります。
ProductID|Product name|Price|Quantity 
ProductID|Product name|Price|Quantity 
ProductID|Product name|Price|Quantity 
次に、ID フィールドを配列キーとして使用します。製品名にも同様のアプローチを使用できますが、スペースや特殊文字を削除する必要があります。
  $raw = file_get_contents($path);
  $raw = explode("\n", $raw);
  $data = array();
  foreach ($raw as $d) {
    $d = explode('|', $d);
    // the left-most data will be our key
    $key = array_shift($d);
    $data[$key] = $d;
  }
これで、次のような配列が得られます (例):
array(
  5=>array(
    'Widget id #5',
    '5.00',
    '2'
  ),
  11=>array(
    'Widget id #11',
    '6.00',
    '1'
  )
)
さらに簡単な方法は、ファイル形式に JSON を使用することです。そうすれば、ファイルからデータを取得した後にデータを解析する必要がなくなり、連想キーを実装するのが簡単になります。どちらの方法でも、同じ手順に従います。
- ファイルからデータを取得して変数に入れる
- 商品がすでにカートに入っているかどうかを確認する
 
- 数量を 1 ずつ増やします (実際にはその他の数値)。
- データをファイルに書き戻す
JSON を使用すると、次のようになります。
$path = 'path/to/data.txt';
$data = json_decode(file_get_contents($path), true);
// if the product isn't in the cart, add it
if (array_key_exists($product_id, $data) === false) {
  // retrieve the product information for $product_id
  // populate $product_name and $product_price
  $data[$product_id] = array(
    'name'=>$product_name,
    'quantity'=>0,
    'price'=>$product_price
  );
}
// increment the quantity
$data[$product_id]['quantity']++;  // $data[$product_id][2]++ if you didn't use JSON
// write the data back into the file
file_put_contents($path, json_encode($data));
ドキュメンテーション