За последние 24 часа нас посетили 114236 программистов и 6445 роботов. Сейчас ищут 1287 программистов ...

Спасайте люди добрые

Тема в разделе "PHP для новичков", создана пользователем Sector22, 17 июн 2016.

  1. Sector22

    Sector22 Новичок

    С нами с:
    17 июн 2016
    Сообщения:
    3
    Симпатии:
    0
    Люди спасайте)) ...есть скрипт...который выбирает инфу с таблицы полученной из 1с, и проверяет с таблицей что уже загружена на сайт, так вот..как можно этот код укоротить, я в php новичок ..поэтому не сильно ругайтесь))

    PHP:
    1. <?php
    2. traitSync1C {
    3.     protected
    4.     function API_setstoreactualityfull()
    5.     {
    6.         set_time_limit(0);
    7.         $fh = fopen('//API_setstoreactualityfull.txt', 'w');
    8.         fwrite($fh, file_get_contents('php://input'));
    9.         fclose($fh);
    10.         $fh = fopen('//API_setstoreactualityfull.txt', 'r');
    11.         $incData = fread($fh, filesize('//API_setstoreactualityfull.txt'));
    12.         fclose($fh);
    13.         $incData = json_decode($incData);
    14.         if (!$incData || $incData == '') $this->_terminateByError('setstoreactuality: Данные не получены!');
    15.         $t = '#type';
    16.         $v = '#value';
    17.         $this->SQL->query("DROP TABLE IF EXISTS _tmp_products_1c");
    18.         $this->SQL->query("DROP TABLE IF EXISTS _tmp_products_stores_quantity");
    19.         $this->SQL->query("CREATE TABLE _tmp_products_1c LIKE products_1c");
    20.         $this->SQL->query("CREATE TABLE _tmp_products_stores_quantity LIKE products_stores_quantity");
    21.         $this->SQL->query("ALTER TABLE `_tmp_products_1c` AUTO_INCREMENT=1");
    22.         $incData = $incData->$v;
    23.         $posStruct = $this->SQL->struct('products_1c');
    24.         unset($posStruct['record_id']);
    25.         unset($posStruct['record_datetime']);
    26.         $transform = ['id' => 'product_1c_id', 'art' => 'product_article', 'brand' => 'product_brand', 'name' => 'product_name', 'store_quantity' => 'store_quantity', 'unit' => 'product_unit', 'store_id' => 'store_id', 'buy_price' => 'buy_price', 'sell_price' => 'sell_price', ];
    27.         $failArticle = [];
    28.         $storeList = [];
    29.         $posQuantity = $storesExists = $storesAdded = $rowsWithoutId1c = $posAddes = 0;
    30.         $incDataStores = $incData->row[0][0]->$v;
    31.         $incData = $incData->row[0][1]->$v;
    32.         $result = ['positions' => [], 'quantity' => []];
    33.         foreach($incDataStores as $key => $store) {
    34.             $store = $store->$v;
    35.             $code = $this->SQL->protect(trim($store[0]->Value->$v));
    36.             $name = $this->SQL->protect(trim($store[1]->Value->$v));
    37.             $storeList[$code] = ['name' => $name, '1c_id' => $code, 'id' => '', ];
    38.             $storeList[$code]['id'] = $this->SQL->getRow("SELECT * FROM products_stores WHERE store_1c_id = '$code'");
    39.             if (!empty($storeList[$code]['id'])) {
    40.                 $storeList[$code]['id'] = $storeList[$code]['id']['store_id'];
    41.                 $storesExists++;
    42.             }
    43.             else {
    44.                 $storesAdded++;
    45.                 $storeList[$code]['id'] = $this->SQL->insert('products_stores', ['store_1c_id' => $code, 'store_name' => $name, ]);
    46.             }
    47.         }
    48.  
    49.         foreach($incData as $index => $data) {
    50.             unset($incData[$index]);
    51.             $pos = $posStruct;
    52.             foreach($data->$v as $col) {
    53.                 $cname = strtolower($col->name->$v);
    54.                 $cval = $col->Value->$v;
    55.                 $cval = $this->SQL->protect(trim($cval));
    56.                 if (isset($transform[$cname])) $pos[$transform[$cname]] = $cval;
    57.             }
    58.  
    59.             if ($pos['product_1c_id'] != '') {
    60.                 if ($pos['product_article'] == '') {
    61.                     $failArticle[] = $pos['product_1c_id'];
    62.                 }
    63.                 else {
    64.                     $idQuery = "SELECT DISTINCT
    65. product_id
    66. FROM products_articles
    67. WHERE ( sku = '1c:$pos[product_article]' OR sku = '$pos[product_article]' ) AND available = 1";
    68.                     $pos['product_id'] = $this->SQL->getRow($idQuery);
    69.                     if (!isset($pos['product_id']['product_id'])) {
    70.                         $failArticle[] = $pos['product_1c_id'];
    71.                     }
    72.                     else {
    73.                         $pos['product_id'] = $pos['product_id']['product_id'];
    74.                     }
    75.                 }
    76.  
    77.                 $pos['store_id'] = $storeList[$pos['store_id']]['id'];
    78.                 $result['quantity'][$pos['product_1c_id']][$pos['store_id']] = $pos['store_quantity'];
    79.                 unset($pos['store_id']);
    80.                 unset($pos['store_quantity']);
    81.                 $result['positions'][$pos['product_1c_id']] = $pos;
    82.                 unset($pos);
    83.                 $posQuantity++;
    84.             }
    85.             else {
    86.                 $rowsWithoutId1c++;
    87.             }
    88.         }
    89.  
    90.         foreach($result['positions'] as $key1c => $pos) {
    91.             $recordId = $this->SQL->insert('_tmp_products_1c', $pos);
    92.             if (isset($result['quantity'][$key1c]) && !empty($result['quantity'][$key1c])) {
    93.                 foreach($result['quantity'][$key1c] as $storeId => $quant) {
    94.                     $this->SQL->insert('_tmp_products_stores_quantity', ['products_1c_rec_id' => $recordId, 'store_id' => (int)$storeId, 'store_quantity' => (float)$quant, ]);
    95.                 }
    96.             }
    97.  
    98.             unset($result['quantity'][$key1c]);
    99.             unset($result['positions'][$key1c]);
    100.             unset($pos);
    101.         }
    102.  
    103.         $this->SQL->query("DELETE FROM products_1c");
    104.         $this->SQL->query("INSERT INTO products_1c SELECT * FROM _tmp_products_1c");
    105.         $this->SQL->query("DELETE FROM products_stores_quantity");
    106.         $this->SQL->query("INSERT INTO products_stores_quantity SELECT * FROM _tmp_products_stores_quantity");
    107.         $this->SQL->query("DROP TABLE _tmp_products_1c");
    108.         $this->SQL->query("DROP TABLE _tmp_products_stores_quantity");
    109.         $this->_terminateBySuccess(['stores_exists' => $storesExists, 'stores_addes' => $storesAdded, 'total_products' => $posQuantity + $rowsWithoutId1c, 'available_products' => $posQuantity, 'filed_empty_id' => $rowsWithoutId1c, 'failed_articles' => count($failArticle) , 'failed_articles_list' => $failArticle, ]);
    110.     }
    111. }
    112.  
    113. ?>
     
    #1 Sector22, 17 июн 2016
    Последнее редактирование модератором: 17 июн 2016
  2. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.497
    Симпатии:
    1.726
    Это никто вычитывать не будет. Вставь код правильно:
    upload_2016-6-17_16-22-16.png
     
  3. mr.akv

    mr.akv Активный пользователь

    С нами с:
    31 мар 2015
    Сообщения:
    1.599
    Симпатии:
    206
    для чего его укорачивать, если он работает?
     
  4. Sector22

    Sector22 Новичок

    С нами с:
    17 июн 2016
    Сообщения:
    3
    Симпатии:
    0
    дабы не было такого дерева ..и начальник сказал надо сделать) я думаю ради моего обучения )
     
  5. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.213
    Симпатии:
    1.711
    Адрес:
    Молдова, г.Кишинёв
    @Sector22 почему код не отформатирован?
     
  6. Sector22

    Sector22 Новичок

    С нами с:
    17 июн 2016
    Сообщения:
    3
    Симпатии:
    0
    Извините
    Код (Text):
    1. <?php
    2.    
    3.     trait Sync1C {
    4.  
    5.         protected function API_setstoreactualityfull() {
    6.             set_time_limit(0);
    7.             $fh = fopen( '//API_setstoreactualityfull.txt', 'w' );
    8.             fwrite( $fh, file_get_contents('php://input') );
    9.             fclose($fh);
    10.             $fh = fopen( '//API_setstoreactualityfull.txt', 'r' );
    11.             $incData = fread( $fh, filesize('//logs/API_setstoreactualityfull.txt') );
    12.             fclose($fh);
    13.             $incData = json_decode( $incData );
    14.             if ( !$incData || $incData == '' ) $this->_terminateByError('setstoreactuality: Данные не получены!');
    15.             $t = '#type';
    16.             $v = '#value';
    17.  
    18.             $incData = $incData->$v;
    19.             $posStruct = $this->SQL->struct('orders_states');
    20.             unset( $posStruct['stateId'] );
    21.             unset( $posStruct['stateCode'] );
    22.             unset( $posStruct['stateCode1c'] );
    23.             unset( $posStruct['stateName'] );
    24.             $transform = [
    25.                 'id' => 'stateId',
    26.                 'art' => 'stateCode',
    27.                 'brand' => 'stateCode1c',
    28.                 'name' => 'stateName',
    29.                 'store_quantity' => 'store_quantity',
    30.                 'unit' => 'product_unit',
    31.                 'store_id' => 'store_id',
    32.                 'buy_price' => 'buy_price',
    33.                 'sell_price' => 'sell_price',
    34.             ];
    35.             $failArticle = [];
    36.             $storeList = [];
    37.             $posQuantity = $storesExists = $storesAdded = $rowsWithoutId1c = $posAddes = 0;
    38.             $incDataStores = $incData->row[0][0]->$v;
    39.             $incData = $incData->row[0][1]->$v;
    40.             $result = [ 'positions' => [], 'quantity' => [] ];
    41.             foreach ($incDataStores as $key => $store) {
    42.                 $store = $store->$v;
    43.                 $code = $this->SQL->protect( trim( $store[0]->Value->$v ) );
    44.                 $name = $this->SQL->protect( trim( $store[1]->Value->$v ) );
    45.                 $storeList[ $code ] = [
    46.                     'name' => $name,
    47.                     '1c_id' => $code,
    48.                     'id' => '',
    49.                 ];
    50.                 $storeList[ $code ][ 'id' ] = $this->SQL->getRow( "SELECT * FROM products_stores WHERE store_1c_id = '$code'" );
    51.                 if ( !empty( $storeList[ $code ][ 'id' ] ) ) {
    52.                     $storeList[ $code ][ 'id' ] = $storeList[ $code ][ 'id' ][ 'store_id' ];
    53.                     $storesExists++;
    54.                 } else {
    55.                     $storesAdded++;
    56.                     $storeList[ $code ][ 'id' ] = $this->SQL->insert( 'products_stores', [
    57.                             'store_1c_id' => $code,
    58.                             'store_name' => $name,
    59.                         ] );
    60.                 }
    61.             }
    62.             foreach ($incData as $index => $data) {
    63.                 unset( $incData[ $index ] );
    64.                 $pos = $posStruct;
    65.                 foreach ($data->$v as $col) {
    66.                     $cname = strtolower( $col->name->$v );
    67.                     $cval = $col->Value->$v;
    68.                     $cval = $this->SQL->protect( trim( $cval ) );
    69.                     if ( isset( $transform[ $cname ] ) ) $pos[ $transform[ $cname ] ] = $cval;
    70.                 }
    71.                 if ( $pos['product_1c_id'] != '' ) {
    72.                     if ( $pos['product_article'] == '' ) {
    73.                         $failArticle[] = $pos['product_1c_id'];
    74.                     } else {
    75.                         $idQuery = "SELECT DISTINCT
    76.                                         product_id
    77.                                     FROM products_articles
    78.                                     WHERE ( sku = '1c:$pos[product_article]' OR sku = '$pos[product_article]' ) AND available = 1";
    79.                         $pos['product_id'] = $this->SQL->getRow( $idQuery );
    80.                         if ( !isset($pos['product_id']['product_id']) ) {
    81.                             $failArticle[] = $pos['product_1c_id'];
    82.                         } else {
    83.                             $pos['product_id'] = $pos['product_id']['product_id'];
    84.                         }
    85.                     }
    86.                     $pos[ 'store_id' ] = $storeList[ $pos[ 'store_id' ] ]['id'];
    87.                     $result['quantity'][ $pos['product_1c_id'] ][ $pos['store_id'] ] = $pos['store_quantity'];
    88.                     unset( $pos['store_id'] );
    89.                     unset( $pos['store_quantity'] );
    90.                     $result['positions'][ $pos['product_1c_id'] ] = $pos;
    91.                     unset( $pos );
    92.                     $posQuantity++;
    93.                 } else {
    94.                     $rowsWithoutId1c++;
    95.                 }
    96.             }
    97.             foreach ($result['positions'] as $key1c => $pos) {
    98.                 $recordId = $this->SQL->insert( '_tmp_products_1c', $pos );
    99.                 if ( isset( $result['quantity'][ $key1c ] ) && !empty( $result['quantity'][ $key1c ] ) ) {
    100.                     foreach ($result['quantity'][ $key1c ] as $storeId => $quant) {
    101.                         $this->SQL->insert( '_tmp_products_stores_quantity', [
    102.                             'products_1c_rec_id' => $recordId,
    103.                             'store_id' => (int)$storeId,
    104.                             'store_quantity' => (float)$quant,
    105.                         ] );
    106.                     }
    107.                 }
    108.                 unset( $result['quantity'][ $key1c ] );
    109.                 unset( $result['positions'][ $key1c ] );
    110.                 unset( $pos );
    111.             }
    112.  
    113.             $this->SQL->query( "DELETE FROM products_1c" );
    114.             $this->SQL->query( "INSERT INTO products_1c SELECT * FROM _tmp_products_1c" );
    115.             $this->SQL->query( "DELETE FROM products_stores_quantity" );
    116.             $this->SQL->query( "INSERT INTO products_stores_quantity SELECT * FROM _tmp_products_stores_quantity" );
    117.             $this->SQL->query( "DROP TABLE _tmp_products_1c" );
    118.             $this->SQL->query( "DROP TABLE _tmp_products_stores_quantity" );
    119.  
    120.             $this->_terminateBySuccess([
    121.                 'stores_exists'=>$storesExists,
    122.                 'stores_addes'=>$storesAdded,
    123.                 'total_products'=>$posQuantity+$rowsWithoutId1c,
    124.                 'available_products'=>$posQuantity,
    125.                 'filed_empty_id'=>$rowsWithoutId1c,
    126.                 'failed_articles'=>count($failArticle),
    127.                 'failed_articles_list'=>$failArticle,
    128.             ]);
    129.         }
    130.  
    131.     }
    132.  
    133. ?>
     
  7. askanim

    askanim Старожил

    С нами с:
    7 апр 2016
    Сообщения:
    2.178
    Симпатии:
    161
    Адрес:
    GABRIEL
    Хочешь ускориться записывай, из 1с в базу MySQL. А потом уже у себя в коде и проверяй. А то у тебя там куча не понятного кода, ты бы хоть прокомментировал пошагово что ты делаешь... А то гадание на 7 камнях, не айс.
    --- Добавлено ---
    А то исходя из того что ты написал чувак. То тут ты можешь получить массив из базы. 1С и Массив из таблицы

    PHP:
    1. $result = array_diff($Выборка1, $Выборка2);
    2. if (!empty($result)) {
    3.    // То твои массивы различны, а значит делай дальше уже что тебе надо.
    4.  
    5.  
    6. }