0

有一个类似 [1] 的数组

$arr = array(
        array(
            "ignoreMe" => "123",
            "checkMe" => "value",
        ),
        array(
            "ignoreMe" => "456",
            "checkMe" => "value",
        ),
 );

我想检查checkMe内部数组的特殊键(此处为 key )是否具有相同的值。如果所有键都具有相同的值,那么我想从内部数组中删除键。(来自所有数组)

但是当有一个像 [2] 这样的数组时

$arr = array(
        array(
            "ignoreMe" => "123",
            "checkMe" => "value",
        ),
        array(
            "ignoreMe" => "456",
            "checkMe" => "value",
        ),
        array(
            "ignoreMe" => "789",
            "checkMe" => "foo", 
        ),
 );

所有的钥匙都应该完好无损。

我将如何使用这个复杂的验证器来做到这一点?(链接https://github.com/Respect/Validation

[1] 的预期结果是

$arr = array(
        array(
            "ignoreMe" => "123",
        ),
        array(
            "ignoreMe" => "456",
        ),
 );

[2] 不应触碰

这是已经尝试过的:

$validator = v::arr()->each(v::key("check", v::equals('value')));
4

1 回答 1

2

好的,如果您正在运行 PHP 5.5+,那么您可以使用array_columnarray_unique函数的组合从数组中删除项目,如果它们都具有相同的值:

我不确定到底会调用什么这样的函数,所以我只是调用它myFunc......

function myFunc(array $arr, $key)
{
    // Get all the values using a key
    $values = array_column($arr, $key);

    // Remove all duplicates
    $unique = array_unique($values);

    // If there only is one item left then it means
    // that all the values are the same, so proceed
    // with modifying it...
    if (count($unique) === 1) {

        // Go over each array...
        foreach ($arr as $x => & $value) {

            // And unset the key
            unset($value[$key]);
        }
    }
    // Return the array
    return $arr;
}

例子:

$arr1 = array(
    array("ignoreMe" => "123", "checkMe" => "value"),
    array("ignoreMe" => "456", "checkMe" => "value"),
);
$arr2 = array(
    array("ignoreMe" => "123", "checkMe" => "value"),
    array("ignoreMe" => "456", "checkMe" => "value"),
    array("ignoreMe" => "789", "checkMe" => "foo"),
);

// All the values in this array are the same, so they
// will be removed
var_dump($arr1);
var_dump(myFunc($arr1, 'checkMe'));
echo '<hr>';

// There is a value in this array that is not the same
// as the others, so this array will be left intact
var_dump($arr2);
var_dump(myFunc($arr2, 'checkMe'));
于 2014-11-11T12:41:33.707 回答