php 数组比较取值,该怎么解决
程序员文章站
2022-06-03 21:53:58
...
php 数组比较取值
{ [0]=> string(9) "1_29" [1]=> string(8) "2_334" [2]=> string(4) "1" [3]=> string(4) "2"
[4]=> string(9) "1_30" [5]=> string(8) "5_334" [6]=> string(4) "6" [7]=> string(4) "10" }
用‘-'分开的前面的值在数据里跟没有'-'的值相同就不取这条数据
比如1_29因为数据里有1跟[2]=> string(4) "1"相同就不取
最后结果只有有‘-’且没有重复的
{[5]=> string(8) "5_334" }
------解决方案--------------------
$a=array("1_29","2_334","1","2","1_30","5_334","6","10");
var_dump($a);
$keys=array();
$result=array();
foreach($a as $val){
if(is_numeric($val))
$keys[]=$val;
}
foreach($a as $val){
if(!is_numeric($val)){
$tmp=explode("_",$val);
if(count($tmp)==2&&!in_array($tmp[0],$keys))
$result[]=$val;
}
}
var_dump($result);
?>
输出:
array(8) {
[0]=>
string(4) "1_29"
[1]=>
string(5) "2_334"
[2]=>
string(1) "1"
[3]=>
string(1) "2"
[4]=>
string(4) "1_30"
[5]=>
string(5) "5_334"
[6]=>
string(1) "6"
[7]=>
string(2) "10"
}
array(1) {
[0]=>
string(5) "5_334"
}
------解决方案--------------------
很土的代码,不过结果是你要的.
{ [0]=> string(9) "1_29" [1]=> string(8) "2_334" [2]=> string(4) "1" [3]=> string(4) "2"
[4]=> string(9) "1_30" [5]=> string(8) "5_334" [6]=> string(4) "6" [7]=> string(4) "10" }
用‘-'分开的前面的值在数据里跟没有'-'的值相同就不取这条数据
比如1_29因为数据里有1跟[2]=> string(4) "1"相同就不取
最后结果只有有‘-’且没有重复的
{[5]=> string(8) "5_334" }
------解决方案--------------------
$a=array("1_29","2_334","1","2","1_30","5_334","6","10");
var_dump($a);
$keys=array();
$result=array();
foreach($a as $val){
if(is_numeric($val))
$keys[]=$val;
}
foreach($a as $val){
if(!is_numeric($val)){
$tmp=explode("_",$val);
if(count($tmp)==2&&!in_array($tmp[0],$keys))
$result[]=$val;
}
}
var_dump($result);
?>
输出:
array(8) {
[0]=>
string(4) "1_29"
[1]=>
string(5) "2_334"
[2]=>
string(1) "1"
[3]=>
string(1) "2"
[4]=>
string(4) "1_30"
[5]=>
string(5) "5_334"
[6]=>
string(1) "6"
[7]=>
string(2) "10"
}
array(1) {
[0]=>
string(5) "5_334"
}
------解决方案--------------------
很土的代码,不过结果是你要的.
- PHP code
$Array = array ('1_29', '2_334', '1', '2', '1_30', '5_334', '6', '10' );$ReferArray = array ();$FixArray = array ();$MyArray = array ();foreach ( $Array as $Value ) { if (strpos ( $Value, '_' ) == false) { $ReferArray [] = $Value; } else { $FixArray [] = substr ( $Value, 0, 1 ); $MyArray [] = $Value; }}$FixArray = array_diff ( $FixArray, $ReferArray );foreach ( $FixArray as $Key => $Value ) { echo $MyArray [$Key];}相关文章
相关视频