仅从数组中选择不同的值

时间:2013-09-28 10:05:03

标签: php mysql loops foreach

在这里,我有以下变量$ 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
      ) 
)

但我需要创建仅包含唯一值的第二个数组$国家:

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;
    }
}

但是如何从上述情况中获得唯一值。

任何人都可以帮助我

提前致谢。

EDIT1

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

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

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

例如, 我希望所有的结果都像(像)'印度'那样的国家

5 个答案:

答案 0 :(得分:2)

您正在寻找array_unique功能。

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

答案 1 :(得分: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);

答案 2 :(得分:1)

$commasplit = function ($list) { return explode(',', $list->countries); };
$countrieslist = array_unique(call_user_func_array('array_merge', array_map($commasplit, $countries_list)));

答案 3 :(得分:1)

你可以试试这个

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

An Example.

答案 4 :(得分: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;
        }
    }
}

$ unique国家/地区包含所有找到的国家/地区,没有重复