php - 如何在 php 中重复功能?

完成后是否可以重复功能。例如:我有一个将 mysql 导出到 json 文件的功能,限制为 100 个数据。如果成功创建一个包含 100 个数据的 json 文件。然后它将重复相同的功能以创建 json 文件 100 多个数据(无重复数据),直到数据用完。

我生成 json 文件的代码:

$results = $db->SELECT()
                ->FROM( array(  'MM'=>'M_MEMBER'),
                        array(  'MEMBER_ID'      => 'MM.MEMBER_ID',
                                'FIRST_NAME'     => 'MM.FIRST_NAME',
                                'LAST_NAME'      => 'MM.LAST_NAME',
                                'MEMBER_GROUP'   => 'MM.MEMBER_GROUP',
                                'MEMBER_GROUP1'  => 'MM.MEMBER_GROUP1',
                                'PHONE_NUMBER'   => 'MM.PHONE_NUMBER',
                                'MEMBERSHIP'     => 'MM.MEMBERSHIP',
                                'UPLOAD_DATE'    => 'MM.UPLOAD_DATE',
                                'STATUS'         => 'MM.STATUS'
                             )
                      )
                ->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
                ->WHERE('SYNC_FLAG = ?','N')
                ->LIMIT(100)
                ->QUERY()->FETCHALL();

if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
    $counter = formatNbr($counterFile);
    $data = array();
    foreach ($results as $key=>$row) {
        $data[$key]         = $row;
        $data[$key]['_id']  = (string) Application_Helper_General::generateIdJsonFile();

        $queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
         $db->query($queryUdateMemberFlag);
    }

    $out  = array_values($data);
    $jsonAr = json_encode($out);
    $json = substr($jsonAr, 1, -1);
    $jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
    $file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
    $createJson = file_put_contents($file, $jsonData);

    if($createJson){
        echo "Create Json File Success In :".$file;

    }else{
        echo "Create Json Failed";
    }
}

代码只能生成一次json文件,生成成功json文件后怎么重复

注意:我为每个成功生成数据的 json 文件添加了一个标志

回答1

您可以将代码提取到函数中并在循环中使用该函数。

例子:

function exporter($limit = 100)
{
    $results = $db->SELECT()
                ->FROM( array(  'MM'=>'M_MEMBER'),
                        array(  'MEMBER_ID'      => 'MM.MEMBER_ID',
                                'FIRST_NAME'     => 'MM.FIRST_NAME',
                                'LAST_NAME'      => 'MM.LAST_NAME',
                                'MEMBER_GROUP'   => 'MM.MEMBER_GROUP',
                                'MEMBER_GROUP1'  => 'MM.MEMBER_GROUP1',
                                'PHONE_NUMBER'   => 'MM.PHONE_NUMBER',
                                'MEMBERSHIP'     => 'MM.MEMBERSHIP',
                                'UPLOAD_DATE'    => 'MM.UPLOAD_DATE',
                                'STATUS'         => 'MM.STATUS'
                             )
                      )
                ->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
                ->WHERE('SYNC_FLAG = ?','N')
                ->LIMIT($limit)
                ->QUERY()->FETCHALL();

        if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
        {
            $counter = formatNbr($counterFile);
            $data = array();
            foreach ($results as $key=>$row) {
                $data[$key]         = $row;
                $data[$key]['_id']  = (string) Application_Helper_General::generateIdJsonFile();

            $queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
             $db->query($queryUdateMemberFlag);
        }

        $out  = array_values($data);
        $jsonAr = json_encode($out);
        $json = substr($jsonAr, 1, -1);
        $jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
        $file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
        $createJson = file_put_contents($file, $jsonData);

        if($createJson) {
            echo "Create Json File Success In :".$file;
        } else {
            echo "Create Json Failed";
        }
}

$numberOfRows = 10000; # use the count query here
$limit = 100;

while($numberOfRows > 0) {
    exporter($limit);
    $numberOfRows -= $limit;
}

此外,您可以在函数中递归调用函数 (https://www.w3schools.blog/php-recursive-functions)

回答2

将现有代码放入循环中似乎是显而易见的答案。

do {
    $results = $db
        ->SELECT()
        ->FROM(
            ['MM'=>'M_MEMBER'],
            [
                'MEMBER_ID'      => 'MM.MEMBER_ID',
                'FIRST_NAME'     => 'MM.FIRST_NAME',
                'LAST_NAME'      => 'MM.LAST_NAME',
                'MEMBER_GROUP'   => 'MM.MEMBER_GROUP',
                'MEMBER_GROUP1'  => 'MM.MEMBER_GROUP1',
                'PHONE_NUMBER'   => 'MM.PHONE_NUMBER',
                'MEMBERSHIP'     => 'MM.MEMBERSHIP',
                'UPLOAD_DATE'    => 'MM.UPLOAD_DATE',
                'STATUS'         => 'MM.STATUS',
            ]
        )
        ->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
        ->WHERE('SYNC_FLAG = ?','N')
        ->LIMIT(100)
        ->QUERY()
        ->FETCHALL();

    if (count($results) === 0) {
        break;
    }

    $data = [];
    foreach ($results as $row) {
        $row['_id']  = (string) Application_Helper_General::generateIdJsonFile();
        $data[] = $row;

        //
        // this is UNSAFE and inefficient, use a prepared statement if possible
        //
        $queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
        $db->query($queryUdateMemberFlag);
    }

    $json = json_encode($out);
    $filename = sprintf(
        "%sdataMember_%s_%s.json",
        $store_path_pos,
        date("Y-m-d"),
        formatNbr($counterFile)
    );

    if ($json && file_put_contents($filename, $json)) {
        echo "Create Json File Success In $file";
    } else {
        echo "Create Json Failed";
    }
} while (true);

我修复了您代码中的一些低效率问题;我不知道您使用的是什么数据库库,但作为一项规则,您永远不应该将变量注入 SQL 查询。在这种情况下它可能是安全的,但是如果您的库允许您应该在循环外准备语句并在循环内执行它以获得更好的性能。

相似文章