复杂的PHP算法

时间:2014-12-31 06:30:25

标签: php arrays algorithm merge

我有以下数组

User Phone cannot be blank. on Rows 2
User Status must be a number. on Rows 2
User Phone cannot be blank. on Rows 3
User Status must be a number. on Rows 3
User Phone cannot be blank. on Rows 4
User Status must be a number. on Rows 4
User Phone cannot be blank. on Rows 5
User Status must be a number. on Rows 5
User Phone cannot be blank. on Rows 6
User Status must be a number. on Rows 6
User Phone cannot be blank. on Rows 7
User Status must be a number. on Rows 7
User Phone cannot be blank. on Rows 8
User Status must be a number. on Rows 8

我想将类似的语句合并到类似于

的语句中
User Phone cannot be blank. on Rows 2,3,4,5,6,7,8
User Status must be a number. on Rows 2,3,4,5,6,7,8

请协助设计此类逻辑

1 个答案:

答案 0 :(得分:3)

这是您可以使用的示例:

$errors = array(
        'User Phone cannot be blank. on Rows 2',
        'User Status must be a number. on Rows 2',
        'User Phone cannot be blank. on Rows 3',
        'User Status must be a number. on Rows 3',
        'User Phone cannot be blank. on Rows 4',
        'User Status must be a number. on Rows 4',
        'User Phone cannot be blank. on Rows 5',
        'User Status must be a number. on Rows 5',
        'User Phone cannot be blank. on Rows 6',
        'User Status must be a number. on Rows 6',
        'User Phone cannot be blank. on Rows 7',
        'User Status must be a number. on Rows 7',
        'User Phone cannot be blank. on Rows 8',
        'User Status must be a number. on Rows 8');

$combined = array();
foreach ($errors as $i => $str) {
    $matches = array();
    if (preg_match('/^(.*)([0-9]+)$/', $str, $matches)) {
        $message = $matches[1];
        $row = $matches[2];
        if (!isset($combined[$message]))
            $combined[$message] = array();
        $combined[$message][] = $row;
    } else
        $combined[] = $str;
}

foreach ($combined as $msg => $rows)
    echo htmlspecialchars($msg) . (is_array($rows) ? implode(',',$rows) : '') . "<br/>\n";

输出:

  

用户手机不能为空。在2,3,4,5,6,7,8行用户状态   必须是一个数字。在第2,3,4,5,6,7,8行