我的原始代码是:

$sc = 'hello 8491241 some text 6254841 some text 568241';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);

$all_matches = $matches1[0];

foreach ($all_matches as $match)
{
   $sid = '9';

   $rov['batch'] = $match;
   $rov['scid'] = $sid;
   $res[] = $rov;
}

print_r($res);

如何将新的命名键['type']添加到preg_match_all的$matches1中,以便在foreach中调用它并给出最终输出:
Array
(
    [0] => Array
        (
            [batch] => 8491241
            [type] => 1
            [scid] => 9
        )

    [1] => Array
        (
            [batch] => 568241
            [type] => 1
            [scid] => 9
        )

    [2] => Array
        (
            [batch] => 6254841
            [type] => 1
            [scid] => 9
        )
)

我尝试的是:
$sc = 'hello 8491241 some text 6254841 some text 568241';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);

$pr_matches1['batch'] = $matches1[0];
$pr_matches1['type'] = 1;
$all_matches[] = $pr_matches1;

foreach ($all_matches as $match)
{
   $sid = '9';

   $rov['batch'] = $match['batch'];
   $rov['type'] = $match['type'];
   $rov['scid'] = $sid;
   $res[] = $rov;
}

print_r($res);

但它给了我错误的输出
http://pastebin.com/WXGpLTX9
你知道吗?

最佳答案

您可以使用array_map()来“扩展”每个匹配项:

$all_matches = array_map(function($match) {
    return [
      'batch' => $match,
      'type' => 1,
      'scid' => 9,
    ];
}, $matches1[0]);

关于php - 在preg_match_all的匹配项中添加新的命名键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28620563/

10-10 23:53