【问题标题】:Complex PHP Algorithm复杂的 PHP 算法
【发布时间】:2015-02-27 07:23:42
【问题描述】:

我有以下数组

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

请协助设计这样的逻辑

【问题讨论】:

    标签: php arrays algorithm merge


    【解决方案1】:

    这是您可以使用的示例:

    $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 行

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多