现在的位置: 首页 > 综合 > 正文

php 简单数组问题

2017年09月13日 ⁄ 综合 ⁄ 共 688字 ⁄ 字号 评论关闭

问题:Array ( [0] => [1] => 3 2 [2] => 4 5 [3] => 3 4 [4] => 2 3 [5] => 1 2 )

我想检查数组当中是否存在两个数是相反的:比如3 2 和2 3

2 3 之间是空格隔开

 

自己写了一个简单的:

foreach($array as $value) {
    $v=explode(" ",$value);
     foreach($array as $num){
    	$m=explode(" ",$value);
    	if($m[0]==$v[1]&&$m[1]==$v[0]){
    		return "get";
    	}
    }
    
}

感觉用了两次foreach和explode,代码冗余,效率不高。

后来论坛发帖,有人这样写:

foreach($array as $value) {
    $v=explode(" ",$value);
      foreach($array as $num){
    	if(strcmp($value,strrev($num))==0){
    		return "get";
    	}
    }
    
}

但还是两次foreach

 

后来又有人回帖:

foreach($ar as $v) {
  $t[] = join(' ', array_reverse(explode(' ', $v)));
}
print_r(array_intersect($ar, $t));

 

方法确实不错:

$tmp = array();
 foreach($arr as $item) {
  $newItem = implode(' ', array_reverse(explode(' ', $item)));
  if(isset($tmp[$newItem])) {
   echo 'you get it!';
   print_r($newItem);
  }
  $tmp[$item] = true;
 } 

 

【上篇】
【下篇】

抱歉!评论已关闭.