0

在这里,我有以下变量 $countries_all:

Array ( 
  [0] => stdClass Object 
      ( 
          [countries] => India,Afghanestan,Japan,South Africa
      ) 
  [1] => stdClass Object 
      ( 
          [countries] => Singapore,South Africa,India,Pakistan
      )
  [2] => stdClass Object 
      ( 
          [countries] => Japan,Australia,India
      ) 
)

但我需要创建第二个数组 $countries 只包含唯一值:

Array ( 
  [0] => stdClass Object 
      ( 
          [countries] => India
      )
  [1] => stdClass Object 
      ( 
          [countries] => Afghanestan
      )
  [2] => stdClass Object 
      ( 
          [countries] => Japan
      )
  [3] => stdClass Object 
      ( 
          [countries] => South Africa
      )
  [4] => stdClass Object 
      ( 
          [countries] => Singapore
      )
  [5] => stdClass Object 
      ( 
          [countries] => Pakistan
      )
  [6] => stdClass Object 
      ( 
          [countries] => Japan
      )
  [7] => stdClass Object 
      ( 
          [countries] => Australia
      ) 
)

对于按 (,) 分割,我使用了以下方法

foreach ($countries_all as $list){
    $countrieslist=explode(',', $list->countries);
    foreach ($countrieslist as $uni_countries){
        echo $uni_countries;
    }
}

但是如何从上述案例中获取唯一值。

谁能帮助我

提前致谢。

编辑1

在这里,我还有一个与上述问题相关的查询。

现在我得到了独特的价值观,

我如何从该唯一值的数据库中获取结果

例如,我想要所有具有(喜欢)国家为“印度”的结果

4

5 回答 5

2

array_unique函数是您正在寻找的。

$countries = array();
foreach ($countries_all as $list){
    $countrieslist=explode(',', $list->countries);
    foreach ($countrieslist as $country){
        $countries[] = $country;
    }
}
$countries = array_unique($countries);
于 2013-09-28T10:13:00.533 回答
1
$newlist = array();
foreach ($countries_list as $list){
    $countrieslist=explode(',', $list->countries);
    foreach ($countrieslist as $uni_countries){
        echo $uni_countries;
        $newlist[] = $uni_countries){
    }
}
array_unique($newlist);
于 2013-09-28T10:12:12.247 回答
1
$commasplit = function ($list) { return explode(',', $list->countries); };
$countrieslist = array_unique(call_user_func_array('array_merge', array_map($commasplit, $countries_list)));
于 2013-09-28T10:14:48.703 回答
1

你可以试试这个

$countrieslist = array();
foreach ($countries_all as $list){
    $countrieslist[] = explode(',', $list->countries);
}
$array = array_unique(array_reduce($countrieslist,'array_merge', array()));

一个例子。

于 2013-09-28T10:19:36.183 回答
0

尝试这个:

$uniqueCountries = array();

foreach ($countries_list as $list){
    $countrieslist=explode(',', $list->countries);
    foreach ($countrieslist as $country){
        if (!in_array($country, $uniqueCountries)) {
            //adding to list
            $uniqueCountries[] = $country
        } else {
             echo $country, ' already in list', PHP_EOL;
        }
    }
}

$uniqueCoutries 包含所有找到的 coutries,没有重复

于 2013-09-28T10:12:55.110 回答