从php中的复杂数组中获取元素名称

时间:2014-06-24 17:02:27

标签: php arrays zend-framework2

我的PHP知识不足以处理这样一个复杂的数组。我在表单验证时在我的Zend Framework 2.3应用程序中使用它,并希望列出所有错误,而不是在下面的输入字段中显示每个错误。

这是我得到的数组

Array ( 
       [email] => Array ( 
                         [isEmpty] => Value is required and can't be empty 
                         [someElse] => Some other message
                         ) 
       [subject] => Array ( 
                           [stringLengthTooLong] => The input is more than 128 characters long 
                           ) 
       [content] => Array ( 
                           [isEmpty] => Value is required and can't be empty 
                           ) 
       )

这是我到目前为止所尝试的

我知道有类似Key()的东西,但这是我应该使用的吗?

我想获得输出

email - Value is required and...
email - Some other message
Subject - THe input is more than...
content - Value is ..

到目前为止,我已经尝试了

if(isset($errorsMessages)) {
    while (current($errorsMessages)) {
        echo key($errorsMessages);
        next($errorsMessages);  
    }
}

它有效我将获得列表电子邮件,主题,内容。但后来我想读取某些子阵列。我试过了

if(isset($errorsMessages)) {
    while ($fruit_name = current($errorsMessages)) {
        echo key($errorsMessages);
            foreach ($errorsMessages as $i) {
                foreach($i as $j) {
                    echo '<br ./>' . ' - ' . $j;
                }
            }
        next($errorsMessages);  
    }
}

但这是一团糟,我正在获得输出

email
- Value is required and can't be empty
- The input is more than 128 characters long
- Value is required and can't be empty

2 个答案:

答案 0 :(得分:1)

我也使用zf2验证。

如果您正在尝试直接检查阵列内容,则应自行尝试。

一种轻松的方法是检查:

$validatorMessages //suppost the messages are there.

$messageInline = ''; //suppost to be the message without array

//add validation by yourself to check if validatorMessage was not a empty array, becouse it throw a exception if has 0 itens.

foreach($validatorMessage as $input => $messages)
{
    if(count($messages)>0)) { //check if really was a first message

        foreach($messages as $type => $message) { //Here is the magic!

            $messageInline .= sprintf('%s - %s',$input,$message).'<br>'; //setting message and newline.
        }
//please note that the first param pass to sprintf was Input, from the master array indice, and the message was a subsequent item inside the same input value.
    }
 }

if(strlen($messageInline)>0) {
     echo 'Errors Founds: ' . $messageInline;
     return false;
} else {
    return true;
}

答案 1 :(得分:-1)

假设数据只有两层深,你可以像这样嵌套2个foreach循环 foreach ($errors => $key1 as $value1) { foreach ($errors => $key2 as $value2) { echo $key1 . " - " . $value2; } }