如何在PHP中查找数组值是否更改

时间:2014-12-12 09:59:25

标签: php

我们有这样的数组:

Array
(
    [0] => Array
        (
            [HASTANEADI] => MALATYA DEVLET HASTANESİ
            [SEHIR] => Malatya
            [DONEM] => NİSAN 2011
        )

    [1] => Array
        (
            [HASTANEADI] => MALATYA DEVLET HASTANESİ
            [SEHIR] => Malatya
            [DONEM] => MART 2011

        )

    [2] => Array
        (
            [HASTANEADI] => MALATYA DEVLET HASTANESİ
            [SEHIR] => Malatya
            [DONEM] => OCAK 2011

        )

    [3] => Array
        (
            [HASTANEADI] => DENİZLİ DEVLET HASTANESİ
            [SEHIR] => Denizli
            [DONEM] => NİSAN 2011

        )

    [4] => Array
        (
            [HASTANEADI] => DENİZLİ DEVLET HASTANESİ
            [SEHIR] => Denizli
            [DONEM] => MART 2011

        )

    [5] => Array
        (
            [HASTANEADI] => DENİZLİ DEVLET HASTANESİ
            [SEHIR] => Denizli
            [DONEM] => OCAK 2011

        )

我想为HASTANE获得一次DONEM。我想写不是每个HASTANE的DONEM值。因为每个HASTANE都是相同的

所以我尝试了这段代码:

$categories="";
foreach ($hastane as $h) {

     $categories.="'$h['DONEM']',";


    }

 echo $categories;



'NİSAN 2011','MART 2011','OCAK 2011','NİSAN 2011','MART 2011','OCAK 2011',

但我想这样输出:

 'NİSAN 2011','MART 2011','OCAK 2011',

我不想让DONEM的价值观出现。 那我该怎么做呢?

由于

2 个答案:

答案 0 :(得分:1)

一种选择是:

$unique = array();
foreach ($hastane as $h) {
  $unique[$h['DONEM']] = 1;
}

$categories="";
foreach(array_keys($unique) as $donem){
  $categories.= "'{$donem}',";
}

答案 1 :(得分:1)

就像上面的评论一样,一种方法是使用array_unique()。收集所需数组中的所有值,然后应用该函数。要展示它们,只需使用implode()

$DONEM = array();
foreach($array as $values) {
    $DONEM[] = "'" . $values['DONEM'] . "'";
}

$DONEM = array_unique($DONEM);
echo implode(', ', $DONEM);

如果您已经使用PHP 5.5或更高版本,则还可以使用array_column

$DONEM = array_unique(array_column($array, 'DONEM'));
echo implode(', ', $DONEM);