0

I'm trying to make a foreach to add a list of products to a database, but it loops more than it should, and I can't find where is wrong. Its a list of products, today it has 25 products, but it loops 600 times. This is my array (just two products, the other 23 products are exactly equal):

$ab = Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [diffgrid] => Product1
                    [msdatarowOrder] => 0
                )

            [TIMESTAMP] => 
            [DEPARTAMENTO] =>                            
            [CATEGORIA] =>                                         
            [SUBCATEGORIA] =>                                     
            [FABRICANTE] => 
            [CODIGO] => 
            [DESCRICAO] =>
            [DESCRTEC] =>
            [PARTNUMBER] =>
            [EAN] =>
            [GARANTIA] =>
            [PESOKG] =>
            [PRECOREVENDA] =>
            [PRECOSEMST] =>
            [DATAVALIDADEPRECO] =>
            [DISPONIVEL] => 
            [URLFOTOPRODUTO] => 
            [ESTOQUE] => 
            [NCM] =>
            [LARGURA] =>
            [ALTURA] =>
            [PROFUNDIDADE] =>
            [ATIVO] => 
            [SUBSTTRIBUTARIA] => 
            [ORIGEMPRODUTO] =>
            [ESTOQUEDISPONIVEL] =>
        )

    [1] => Array
        (
            [@attributes] => Array
                (
                    [diffgrid] => Produtos2
                    [msdatarowOrder] => 1
                )

            [TIMESTAMP] =>
            [DEPARTAMENTO] =>
            [CATEGORIA] =>                                         
            [SUBCATEGORIA] =>                                      
            [FABRICANTE] => 
            [CODIGO] => 
            [DESCRICAO] =>
            [DESCRTEC] => 
            [PARTNUMBER] =>
            [EAN] =>
            [GARANTIA] =>
            [PESOKG] =>
            [PRECOREVENDA] => 
            [PRECOSEMST] => 
            [DATAVALIDADEPRECO] =>
            [DISPONIVEL] =>
            [URLFOTOPRODUTO] =>
            [ESTOQUE] =>
            [NCM] =>
            [LARGURA] =>
            [ALTURA] =>
            [PROFUNDIDADE] =>
            [ATIVO] =>
            [SUBSTTRIBUTARIA] =>
            [ORIGEMPRODUTO] =>
            [ESTOQUEDISPONIVEL] =>
        )
)

And this is my code (please, ignore the comments in portuguese):

public static function callCurl($method, $url, $body = null)
{
    #$apiUser = Mage::getStoreConfig('allnations/general/api_user', Mage::app()->getStore());
    #$apiPassword = Mage::getStoreConfig('allnations/general/api_password', Mage::app()->getStore());

    $headers = array(
        "Content-type: application/x-www-form-urlencoded",
        "Accept: application/x-www-form-urlencoded"
    );

    $connection = new Varien_Http_Adapter_Curl();

    if ($method == "GET") {
        $zendMethod = Zend_Http_Client::GET;
    } elseif ($method == "POST") {
        $zendMethod = Zend_Http_Client::POST;
    } elseif ($method == "PUT") {
        $zendMethod = Zend_Http_Client::PUT;
        //ADICIONA AS OPTIONS MANUALMENTE POIS NATIVAMENTE O WRITE NAO VERIFICA POR PUT
        $connection->addOption(CURLOPT_CUSTOMREQUEST, "PUT");
        $connection->addOption(CURLOPT_POSTFIELDS, $body);
    }

    $connection->setConfig(
        array(
            'timeout'   => 30
        )
    );

    #Grava, lê e fecha a conexão
    $connection->write($zendMethod, $url, '1.0', $headers, $body);
    $response = $connection->read();
    $connection->close();

    #Extrai o httpcode e o BODY de resposta
    $httpCode = Zend_Http_Response::extractCode($response);
    $response = Zend_Http_Response::extractBody($response);

    #Guarda a resposta em uma variavel diferente e depois decodifica ela
    $arrResp  = $response;
    $response = json_decode($response, true);

    $response['httpCode'] = $httpCode;

    #Transforma a resposta guardada anteriormente em DOMDocument, depois em XML
    $doc = new DOMDocument();
    $doc->preserveWhiteSpace = true;
    $doc->loadXML($arrResp);
    $doc->save('t.xml');

    #Pega o xml e transforma em Array
    $xmlfile  = file_get_contents('t.xml');
    $parseObj = str_replace($doc->lastChild->prefix.':',"",$xmlfile);
    $ob       = simplexml_load_string($parseObj);
    $data     = json_decode(json_encode($ob), true);


    $response = [
        'httpCode' => $response,
        'response' => $data
    ];

    return $response;
}

public static function promoProducts()
{
    $apiUser = Mage::getStoreConfig('allnations/general/api_user', Mage::app()->getStore());
    $apiPassword = Mage::getStoreConfig('allnations/general/api_password', Mage::app()->getStore());

    $url = my url;

    $return = self::callCurl('GET', $url);
    $promo = Mage::getModel('novapc_allnations/promotion');

    $ab = $return['response']['diffgrdiffgram']['NewDataSet']['Produtos'];

    foreach ($ab as $product) {
        $promo->setData(array(
            'name'              => $product['DESCRICAO'],
            'id_product'        => $product['CODIGO'],
            'promo_price'       => $product['PRECOREVENDA'],
            'descrtec'          => $product['DESCRTEC'],
            'category'          => $product['CATEGORIA'],
            'sub_category'      => $product['SUBCATEGORIA'],
            'manufacturer'      => $product['FABRICANTE'],
            'department'        => $product['DEPARTAMENTO'],
            'partnumber'        => $product['PARTNUMBER'],
            'ean'               => $product['EAN'],
            'warranty'          => $product['GARANTIA'],
            'weight'            => $product['PESOKG'],
            'resale_price'      => $product['PRECOREVENDA'],
            'price_without_st'  => $product['PRECOSEMST'],
            'expire_date'       => $product['DATAVALIDADEPRECO'],
            'available'         => $product['DISPONIVEL'],
            'pic'               => $product['URLFOTOPRODUTO'],
            'stock'             => $product['ESTOQUE'],
            'ncm'               => $product['NCM'],
            'width'             => $product['LARGURA'],
            'height'            => $product['ALTURA'],
            'depth'             => $product['PROFUNDIDADE'],
            'active'            => $product['ATIVO'],
            'subst_tributaria'  => $product['SUBSTTRIBUTARIA'],
            'product_origin'    => $product['ORIGEMPRODUTO'],
            'available_stock'   => $product['ESTOQUEDISPONIVEL'],
            'updated_at'        => $product['TIMESTAMP']
            ));
        #$promo->setId(null);
        $promo->save();
        // Pra pegar o primeiro produto: $return[response][diffgrdiffgram][NewDataSet][Produtos][0], o segundo
        // seria o
        // [1], e etc;
    }

}
9
  • what will you get in $ab ? Commented Aug 24, 2017 at 14:52
  • $ab = my array, above the foreach
    – Stordon
    Commented Aug 24, 2017 at 14:56
  • If $ab is looping more than you think it should, it means you have more records in the collection then you think.
    – Eirik
    Commented Aug 24, 2017 at 14:56
  • here is the full array: novapcshop.com.br/ambiente5.php. It has 25 products([0] to [24]). So it should loop 25 times, right? If so, maybe I'm trigering the method more than once? Just tell me if thats a possibility
    – Stordon
    Commented Aug 24, 2017 at 15:00
  • can you please paste your whole code so that we can have clear idea ? Commented Aug 24, 2017 at 15:07

1 Answer 1

1

I'm calling it in an observer just to check if it works. The event is <adminhtml_block_html_before> – Stordon

I guess this is the problem that adminhtml_block_html_before is called multiple (depending on page +20) times ... so 25 * 24?

In your observer you can do something this ...

if ($observer->getBlock()->getType() == 'your/block') {
    # your promoProducts() code
}
2
  • Yeah, that was my guess when I couldn't find the error. Thank you. Can you indicate a way to test it? Maybe another event? And also, for a future reference, this is a method that is gonna be used more than once. Can you please tell me how can I skip duplicates?
    – Stordon
    Commented Aug 24, 2017 at 17:42
  • @Stordon Updated. "Skip duplicates" is bit too broad, maybe use an controller event?
    – sv3n
    Commented Aug 24, 2017 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.