我有一个像这样的PHP数组:
Array
(
[0] => 4-3
[1] => 3-4 // to be removed
[2] => 4-19
[3] => 19-4 // to be removed
[4] => 35-10
[5] => 10-35 // to be removed
[6] => 11-15
)
我想删除所有反转的值,需要这样的结果:
Array
(
[0] => 4-3
[1] => 4-19
[2] => 35-10
[3] => 11-15
)
有人可以帮我吗?在此之前谢谢:)
答案 0 :(得分:0)
您可以使用array_reduce
将数组汇总为关联数组。使用array_values
将关联数组转换为简单数组。
$arr = //your array
$result = array_reduce($arr, function($c, $v){
list( $a, $b ) = explode('-', $v);
if ( !isset( $c[$b . '-' . $a] ) ) $c[$a . '-' . $b] = $v;
return $c;
}, array());
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
这将导致:
Array
(
[0] => 4-3
[1] => 4-19
[2] => 35-10
[3] => 11-15
)
答案 1 :(得分:0)
如果结构始终如图所示,则可以使用
删除每个奇数索引foreach($array as $key => $value) if($key&1) unset($array[$key]);
答案 2 :(得分:-1)
虽然Eddie的解决方案更有趣,但我在这里是怎么回事......
$x = Array
(
0 => '4-3',
1 => '3-4', // to be removed
2 => '4-19',
3 => '19-4', // to be removed
4 => '35-10',
5 => '10-35', // to be removed
6 => '11-15',
);
$y = array();
foreach ($x as $k=>$v) {
$tmp = explode('-',$v);
sort($tmp);
$y[$k] = implode('-',$tmp);
}
$y = array_unique($y);
$y = array_values($y);
echo print_r($y);