0

我有多个不同的数据库字符串,例如一个是:

“苹果,苹果,苹果,橙子,苹果,橙子”

我想将每个字符串动态表示为:

“我有苹果​​和橙子,一共有六个。”

另一个字符串可能是:

“苹果,苹果,苹果,苹果”;

应该说:

“我有苹果​​,一共有四个。”

我将如何在 PHP 中编写脚本?泰来帮忙!

4

2 回答 2

1
<?php
  $str = 'Apples,Apples,Apples,Oranges,Apples,Oranges';

  $arr = explode(',', $str);
  echo 'I have '.implode(' and ', array_unique($arr))
    .  '. There are '.count($arr).' in total.';

这应该是不言自明的,但仅供参考,请参阅:explode, implode&array_unique

于 2013-04-26T18:55:26.433 回答
0

我做了这个测试:

<?php
$data = "Apples,Apples,Apples,Oranges,Apples,Oranges";

$array = explode(",",$data); //array of elements
$count = count($array); //How many elements

$arr_unique = array_unique($array); //array of unique elements

echo "I have ".implode(" and ", $arr_unique). ". There are ".$count." in total.";
//var_dump($arr_unique); //For test
?>

PS:检查小提琴: http: //phpfiddle.org/main/code/3u4-e5v

于 2013-04-26T19:00:45.667 回答