【问题标题】:PHP, MYSQL, FOREACH check if value are all same [duplicate]PHP,MYSQL,FOREACH 检查值是否都相同[重复]
【发布时间】:2016-02-13 08:01:47
【问题描述】:

示例:

Mysql - 表数据

  dataid   dataname    datastatus
    1        joel          1
    1        joelle        2
    1        joe           3
    1        joela         4
    1        joella        5

PHP

 $names = array('joel','joelle','joe','joela');
 foreach($names as $name)
 {
    $qcheck = $this->db->query("SELECT * FROM table_data WHERE dataname=".$name."");
     //Do checking here
 }

我如何知道 joel、joelle、joe 和 joela 数据状态是否都相同和不同?

我怎么知道那个例子的输出..输出应该是假的,因为所有的状态都不一样,如果所有的状态都一样,我怎么知道呢?

希望有人能帮助我提前谢谢..

【问题讨论】:

  • 我没有得到我想要的答案,因为我的问题不准确..我要发布真实场景..

标签: php mysql arrays foreach


【解决方案1】:

更简单的方法是使用array_unique()。如果结果数组只有一个元素,它们都是相同的。

$sample_array = array('Joe','Joe','Joe','Joe');
if (count(array_unique($sample_array)) === 1) {
  echo 'all the same';
}
else {
  echo 'not all the same';
}

输出

all the same

Demo

$arrays = [
    ['Joe','Joe','Joe','Joe'],
    ['Joe','Joe','Joe','John']
];
foreach ($arrays as $array) {
  if (count(array_unique($array)) === 1) {
    echo 'all the same';
  }
  else {
    echo 'not all the same';
  }
  echo "\n";
}

输出

all the same
not all the same

Demo

【讨论】:

  • 你好约翰,你能帮我解决我的问题吗?
【解决方案2】:
$sample_array = array('Joe','Joe','Joe','Joe');
$temp = $sample_array[0];
$same = true;

for($i = 1; $i < count($sample_array); $i++) {
    if ($sample_array[$i] != $temp) {
        $same = false;
        break;
    }
}

if ($same) {
    echo 'All same';
} else {
    echo 'Not same';
}

结果:

All same

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 2018-03-31
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2015-09-06
    • 2018-08-17
    • 1970-01-01
    • 2013-04-16
    相关资源
    最近更新 更多