PHP 比较数组值以进行验证

发布于 2024-10-06 02:08:55 字数 2728 浏览 0 评论 0原文

好的,我有一个非常定制的问题,所以请耐心等待。

我基本上有两组数据,我想将它们与许多不同的可能性进行比较。

$data  = array(
             'object'=>'ball', // Should check VALID (Rule 2)
             'color'=>'white', // VALID (Rule 2)
             'heavy'=>'no',    // VALID (Rule 1)
             'name'=>'wilson', // VALID (Rule 5)
             'funny'=>'no'     // INVALID (Rule 4)
              );

$data_2 = array(
             'object'=>'box',   // VALID (Rule 2)
             'color'=> 'blue',  // VALID (Rule 2)
             'texture'=>'hard', // VALID (Rule 1)
             'heavy'=>'yes',    // INVALID (Rule 4)
             'stupid'=>'no'     // INVALID (Rule 4)
                                // Name is INVALID because it is missing (Rule 3)

);

$required = array(
             'color'=>array('white','blue'),
             'heavy'=> 'no',
             'name'
);

$errors = array(
         'color'=>array('required'=>'Color is Required','invalid'=>'Color invalid')
         'object'=>array('invalid'=>'Object invalid'),
         'texture'=>array('invalid'=>'Texture invalid'),
         'heavy'=>array('required'=>'Heavy is Required','invalid'=>'Heavy invalid'),
         'name'=>array('required'=>'Name is Required','max_char'=>'Name exceeds char limit',
         'invalid'=>'Invalid item provided',          
);

$blueprint = array(
                 'object'=>array('box','ball'),
                 'color'=>array('blue','white'),
                 'texture'=>'hard',
                 'heavy'=>'no',
                 'name'
             );

我想要做的是通过 $blueprint 运行 $data 并确保以下内容:

  1. 如果 $data 键/值对匹配$blueprint 键/值对,$data'sk/v 有效
  2. 如果 $data 键/值对与 匹配$blueprint 键和嵌套数组中的值,$data'sk/v 有效
  3. 如果 $data 数组省略了存在的键/值对在 $blueprint 中,$data'sk/v 可能仍然有效,如果它不在 $required 数组中
  4. ,如果 $data 数组提供了 $blueprint 中不存在的键/值对,$data'sk/v 无效
  5. 如果 $data键/值对中的 键与没有定义键的 $blueprint 值匹配,$data'sk/v 仍然有效。但是,如果$blueprint同时定义了键和值,则$data'sk/v必须满足规则1的要求才有效。
  6. 我想对几个 $blueprint k/v 施加字符限制,如果 $data'sk/v 超出此字符限制,$ datask/v 无效

如果 $data'sk/v 无效,那么我想以某种方式将错误与该特定 k/v 关联起来,描述其无效原因(超出字符限制、一般错误等)也许错误会在第三个数组中定义?

我已经研究过 array_intersect_assoc 但不确定这是否超出了该函数的范围。另外,$blueprint 中会有大量的值,所以我需要尽可能通用的东西。

我认为这是对的,当我写这篇文章时,我的大脑有点融化了,所以如果感到困惑,请随时询问。我最好单独验证每个 k/v 吗?

让我们看看谁是最有头脑的人。

Ok, I have a pretty customized question so bear with me.

I basically have two sets of data that I want to compare with a lot of different possibilities.

$data  = array(
             'object'=>'ball', // Should check VALID (Rule 2)
             'color'=>'white', // VALID (Rule 2)
             'heavy'=>'no',    // VALID (Rule 1)
             'name'=>'wilson', // VALID (Rule 5)
             'funny'=>'no'     // INVALID (Rule 4)
              );

$data_2 = array(
             'object'=>'box',   // VALID (Rule 2)
             'color'=> 'blue',  // VALID (Rule 2)
             'texture'=>'hard', // VALID (Rule 1)
             'heavy'=>'yes',    // INVALID (Rule 4)
             'stupid'=>'no'     // INVALID (Rule 4)
                                // Name is INVALID because it is missing (Rule 3)

);

$required = array(
             'color'=>array('white','blue'),
             'heavy'=> 'no',
             'name'
);

$errors = array(
         'color'=>array('required'=>'Color is Required','invalid'=>'Color invalid')
         'object'=>array('invalid'=>'Object invalid'),
         'texture'=>array('invalid'=>'Texture invalid'),
         'heavy'=>array('required'=>'Heavy is Required','invalid'=>'Heavy invalid'),
         'name'=>array('required'=>'Name is Required','max_char'=>'Name exceeds char limit',
         'invalid'=>'Invalid item provided',          
);

$blueprint = array(
                 'object'=>array('box','ball'),
                 'color'=>array('blue','white'),
                 'texture'=>'hard',
                 'heavy'=>'no',
                 'name'
             );

What I want to do is run $data through the $blueprint and make sure of the following:

  1. If the $data key/value pair matches a $blueprint key/value pair, $data's k/v is valid
  2. If the $data key/value pair matches a $blueprint key and a value from the nested array, $data's k/v is valid
  3. If the $data array omits a key/value pair which exists in $blueprint, $data's k/v may still be valid if it is not located in the $required array
  4. If the $data array supplies a key/value pair which does not exist in $blueprint, $data's k/v is invalid
  5. If the $data key from a key/value pair matches a $blueprint value without a defined key, $data's k/v can still be valid. However, if the $blueprint has both a key and value defined, $data's k/v must meet the requirements of rule 1 to be valid.
  6. I'd like to impose a character limit on several of the $blueprint k/v where if a $data's k/v exceeds this character limit, $datas k/v is not valid

If a $data's k/v is invalid, I'd then like to somehow associate an error with that particular k/v describing why it is invalid (surpassed character limit, general error etc.) Perhaps the error would be defined in a third array?

I've looked into array_intersect_assoc but not sure if this is beyond the scope of that function. Also, there will be a good amount of values in the $blueprint, so I need something as versatile as possible.

I think that this is right, my brain sort of melted while I was writing this, so please don't hesitate to ask if confused. Am I better off just validating each k/v individually?

Let's see who is the brainiac out there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

雅心素梦 2024-10-13 02:09:10

您想使用 in_array()。它将搜索数组的值并找到不同的值,例如。

foreach($data as $key => $val) {
  $check = in_array($val, $blueprint);
  if($check === false) {
    print("invalid");
    die;
  }
}

You want to use in_array(). It will search through the values of your array and find the different values, eg.

foreach($data as $key => $val) {
  $check = in_array($val, $blueprint);
  if($check === false) {
    print("invalid");
    die;
  }
}
花心好男孩 2024-10-13 02:09:10

是的,您可能必须自己编写代码,因为我认为没有任何内部函数可以做到这一点。应该不会太难,因为您已经对您的需求有了很好的描述 - 只需将其翻译成 PHP 即可。

Yes, you probably have to code it youself, as I don't think there is any internal function that can do this. Shouldn't be too hard as you already have a good description of your requirements - just translate it into PHP.

雨夜星沙 2024-10-13 02:09:07

说实话,这本身并不困难,只是复杂。您可以使用 array_map 函数来简化映射;它看起来像这样:

function validate_data($data, $blueprint)
{
    // an implementation of all that stuff you wrote using lots of
    // for loops and if statements
}

array_map('validate_data', $data, $blueprint);

查看手册页了解更多细节。这次你可以成为疯子了:)

Truth be told, that's not that difficult per se, its just complex. You can use the array_map function to simplify the mapping; it would look like this:

function validate_data($data, $blueprint)
{
    // an implementation of all that stuff you wrote using lots of
    // for loops and if statements
}

array_map('validate_data', $data, $blueprint);

Check out the man page for more specifics. You can be the braniac this time :)

鸠书 2024-10-13 02:09:03

我有点愚蠢,但这是一种蛮力的方法。 #6您免费获得,因为它在任何意义上都不是“在”数组中。

foreach ($data as $k => $v) {
    if (empty($blueprint[$k])) {
        // (3) Data defines a key that isn't defined in blueprint.
    } else {
        if (is_array($blueprint[$k])) {
            if (in_array($v, $blueprint[$k])) {
                // (2) Data defines a valid value in a blueprint list.
            } else {
                // (also 4) Data defines a value not in a blueprint list.
            }
        } else if ($v == $blueprint[$k]) {
            // (1) Data defines a value in the blueprint.
        } else if (in_array($v, $blueprint)) {
            // (5) Data is in the blueprint without a key.
        } else {
            // (4) Data is invalid.
        }
    }
}

编辑:这是检查$ blueprint是否具有$ data无法定义的键。可能应该有一个切换,以确保在运行之前(在上一个块中)完全必要。

foreach ($blueprint as $k => $v) {
    if (empty($data[$k])) {
        // (6) Data doesn't have a required key from blueprint.
    }
}

I feel sort of silly, but here's a brute force method. #6 you get for free because it's not 'in' the array in any sense.

foreach ($data as $k => $v) {
    if (empty($blueprint[$k])) {
        // (3) Data defines a key that isn't defined in blueprint.
    } else {
        if (is_array($blueprint[$k])) {
            if (in_array($v, $blueprint[$k])) {
                // (2) Data defines a valid value in a blueprint list.
            } else {
                // (also 4) Data defines a value not in a blueprint list.
            }
        } else if ($v == $blueprint[$k]) {
            // (1) Data defines a value in the blueprint.
        } else if (in_array($v, $blueprint)) {
            // (5) Data is in the blueprint without a key.
        } else {
            // (4) Data is invalid.
        }
    }
}

EDIT: This is the loop for checking if $blueprint has a key that $data doesn't define. There should probably be a toggle to make sure this is at all necessary (in the previous block) before running it.

foreach ($blueprint as $k => $v) {
    if (empty($data[$k])) {
        // (6) Data doesn't have a required key from blueprint.
    }
}
辞旧 2024-10-13 02:09:02

我对您的示例代码进行了更改。如果您将名称添加到键而不是数字键值值中,似乎更容易。

$required = array(
 'color'=>array('white','blue'),
 'heavy'=> 'no',
 'name' => '', # name now a key
);

现在,这适用于您的许多规则。主要检查所需的键,并且不存在所需和蓝图之外的额外键。

# check required keys
$missing = array_diff_key($required, $data);
if($missing) {
  var_dump($missing); # react to missing keys
}

# check against all possible keys
$possible = array_merge_recursive($blueprint, $required);
$extra = array_diff_key($data, $possible);
if($extra) {
  var_dump($extra); # react to extra keys
}

现在,在其余的情况下,我真的需要知道您如何响应错误的数据等。但是,如果您的数据现在通过了这两个测试,并且您以您认为合适的方式做出响应,则应清楚地通过数组迭代并使用<<代码> array_search()和filter_var()检查长度。

I made one change to your sample code. It seems easier if you make name into a key rather than a numerically keyed value.

$required = array(
 'color'=>array('white','blue'),
 'heavy'=> 'no',
 'name' => '', # name now a key
);

This now works for a number of your rules. Primarily checking required keys exist, and that no extra keys outside of required and blueprint exist.

# check required keys
$missing = array_diff_key($required, $data);
if($missing) {
  var_dump($missing); # react to missing keys
}

# check against all possible keys
$possible = array_merge_recursive($blueprint, $required);
$extra = array_diff_key($data, $possible);
if($extra) {
  var_dump($extra); # react to extra keys
}

Now for the rest I would really need to know how you respond to malformed data etc. but if your data now passes these two tests and you respond in the way you see fit, you should be clear to iterate through the array and validate using array_search(), and filter_var() to check lengths.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文