验证PHP数组键>值

时间:2014-11-11 12:09:29

标签: php arrays respect-validation

拥有像[1]

这样的数组
$arr = array(
        array(
            "ignoreMe" => "123",
            "checkMe" => "value",
        ),
        array(
            "ignoreMe" => "456",
            "checkMe" => "value",
        ),
 );

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

但是当有一个像[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')));

1 个答案:

答案 0 :(得分: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'));