PHP数组 - 删除其他反转值

时间:2018-06-08 15:48:38

标签: php arrays

我有一个像这样的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
)

有人可以帮我吗?在此之前谢谢:)

3 个答案:

答案 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
)

文档:array_reduce()array_filter()

答案 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);