我已经存储了一个基于post值的数组,其中存储了多个数组,例如下面的(关键数字可能因用户输入而异):
Array (
[1] => Array
([system] => A [serial]=> 12345L)
[3] => Array
([system] => B [serial] =>)
[4] => Array
([system] => D [serial] => 56789L [licence] => ABCD1-EFGH2-IJKL3-MNOP4-QRST5)
[5] => Array
([serial] => 98765L [licence] => 1234567890)
)
注意:我不确定是否值得一提但是对于上面的例子,数组键是1345,但它可能是123456或56等...
我想检查每个阵列是否都有系统密钥和串行密钥,并且这些密钥都有值。许可证密钥是可选的。
所以理论上我的例子意味着1& 4是有效的,但3不是因为它缺少串行值而且5都没有,因为它没有系统密钥。
由于它在数组内部开始,我有点迷失方向。但是,我已经做了下面的非常基础,我可以想象效率很低。
foreach($sys_arr as $k => $v) {
if (is_array($v) == true) {
foreach($v as $key => $value) {
if ($key = "system" && $value == null) {
echo "Error: System has no value<br>";
} elseif ($key = "serial" && $value == null) {
echo "Error: Serial has no value<br>";
} else {
echo "Both keys have values<br>";
}
}
if (!array_key_exists("system", $v)) {
echo "Error: No System Key<br>";
} elseif (!array_key_exists("serial", $v)) {
echo "Error: No Serial Key<br>";
} else {
echo "Both Keys exist!<br>";
}
}
}
是否有人能就如何改善这一点提出任何建议?
答案 0 :(得分:2)
这应该有效:
$array = [
['system' => 'A', 'serial' => '1232'],
['system' => 'B', 'serial' => ''],
['system' => 'D', 'serial' => '1232', 'licence' => '123123'],
['serial' => '&2312321', 'licence' => '123123']
];
$valid = [];
foreach ($array as $key => $value) {
if (!isset($value['system'])) {
echo 'Error: No System Key<br>';
continue;
}
if (!isset($value['serial'])) {
echo 'Error: No Serial Key<br>';
continue;
}
if (empty($value['system'])) {
echo 'Error: System has no value<br>';
continue;
}
if (empty($value['serial'])) {
echo 'Error: Serial has no value<br>';
continue;
}
$valid[] = $value;
}
var_dump($valid);
答案 1 :(得分:1)
再也不需要再做一次这样的事情
foreach($sys_arr as $k => $v)
{
if (key($v['system']) = "system" && $v['system'] == null)
{
echo "Error: System has no value<br>";
}
elseif (key($v['serial'])= "serial" && $v['serial'] == null)
{
echo "Error: Serial has no value<br>";
}
else
{
echo "Both keys have values<br>";
}
if (!array_key_exists("system", $v))
{
echo "Error: No System Key<br>";
}
elseif (!array_key_exists("serial", $v))
{
echo "Error: No Serial Key<br>";
}
else
{
echo "Both Keys exist!<br>";
}
}