2015-02-15 5 views
0

Я смотрел на это некоторое время, но не могу понять, что не так. Прежде всего, мой код:loop through array не возвращает правильные значения

//Show the products information line by line 
$item_count = 0 ; 
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { 
    $data2[$i][0] = $order->products[$i]['qty']; 

    if (strlen($order->products[$i]['name']) > 40 && strlen($order->products[$i]['name']) < 50){ 
     $data2[$i][1] = $order->products[$i]['name']; 
    } else if (strlen($order->products[$i]['name']) > 50) { 
     $data2[$i][1] = substr($order->products[$i]['name'],0,50); 
    } else { 
     $data2[$i][1] = $order->products[$i]['name']; 
    } 

    $data2[$i][2] = $order->products[$i]['model']; 

    $data2[$i][3] = str_replace('&nbsp;', ' ',$currencies->format($order->products[$i]['final_price'], true, $order->info['currency'], $order->info['currency_value'])); 

    // Add to $data2 if needed (adjust/renumber subsequent array keys!): 

    // For VAT purposes: 
    // Check if product is an 'electronic service'. If so, determine the customer's country. 

    // NOTE (Debug): the comparison of " pov.products_options_values_name = $order->products[$i]['attributes'][$j]['value'] " only holds if the option description is not changed/replaced/deleted. 

    if (isset($order->products[$i]['attributes']) && (($k = sizeof($order->products[$i]['attributes'])) > 0)) { 
     for ($j = 0; $j < $k; $j++) { 
      $virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . $order->products[$i]['id'] . "' and pov.products_options_values_name = '" . $order->products[$i]['attributes'][$j]['value'] . "' and pa.products_attributes_id = pad.products_attributes_id"); 
      $virtual_check = tep_db_fetch_array($virtual_check_query); 
      if ($virtual_check['total'] > 0) { 
       $product_type_check = 'virtual'; 
       $order_type_check = 'virtual or mixed'; 
       break; 
      } 
     } 
    } 

    if ($product_type_check == 'virtual') { 
     if ($customer_country == 'home country') { 
      $data2[$i][4] = str_replace('&nbsp;', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%'); 
     } elseif ($customer_country == 'eu country') { 
      $data2[$i][4] = '***'; 
     } else { 
      $data2[$i][4] = str_replace('&nbsp;', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%'); 
     } 
    } else { 
     $data2[$i][4] = str_replace('&nbsp;', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%'); 
    } 

    unset($product_type_check); 

    //  $data2[$i][3] = str_replace('&nbsp;', ' ',$currencies->format($order->products[$i]['final_price'], true, $order->info['currency'], $order->info['currency_value'])); 

    // Add to $data2 if needed (adjust/renumber subsequent array keys!): 
    //  $data2[$i][5] = str_replace('&nbsp;', ' ',$currencies->format(tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), true, $order->info['currency'], $order->info['currency_value'])); 

    $data2[$i][5] = str_replace('&nbsp;', ' ',$currencies->format($order->products[$i]['final_price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value'])) ; 

    // Add to $data2 if needed (adjust/renumber subsequent array keys!): 
    //  $data2[$i][5] = str_replace('&nbsp;', ' ',$currencies->format(tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value'])); 


    // Show the products attributes 
    $data3 = array(); 

    //get attribs 
    if (isset($order->products[$i]['attributes']) && (($z = sizeof($order->products[$i]['attributes'])) > 0)) { 
     $attribute_line = 'true'; 
     for ($m = 0; $m < $z; $m++) { 
      if ($order->products[$i]['attributes'][$m]['price'] != '0') { 
       if (strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'] . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')') > 50) { 
        $data3[$i][$m][1] = substr('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'],0,40) . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')'; 
       } else { 
        $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'] . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')' ; 
       } 
      } else { 
       if (strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value']) > 50) { 
        $data3[$i][$m][1] = substr('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'],0,50); 
       } else { 
        //  $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value']; 
        $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value']; 
       } 
      } 
     } 
    } 
} 

Код выше должен:

  • Поместите данные общего продукта в массиве $ data2

  • Поместите атрибуты каждого продукта (который может быть более одного) в массив $ data3

В массиве $ order-> products содержится th е следующие данные:

Array (

[0] => Array ( 
[qty] => 1 
[id] => 4 
[name] => Product A 
[model] => 
[tax] => 21.0000 
[price] => 19.9900 
[final_price] => 19.9900 
[attributes] => Array ( 
[0] => Array ( 
[option] => Type 
[value] => X 
[prefix] => + 
[price] => 0.0000 
) 
) 
) 

[1] => Array ( 
[qty] => 1 
[id] => 4 
[name] => Product A 
[model] => 
[tax] => 21.0000 
[price] => 19.9900 
[final_price] => 19.9900 
[attributes] => Array ( 
[0] => Array ( 
[option] => Type 
[value] => Y 
[prefix] => 
[price] => 0.0000 
) 
) 
) 
) 

код вводит следующие данные в массиве $ Data3:

Array ( 
[1] => Array (
[0] => Array (
[1] => - Y 
) 
) 
) 

Это означает, что атрибуты первого продукта (продукт А с ключом 0 в $ заказе запасного > массив продуктов отсутствует!

Чувство кишки подсказывает мне, что код уже перемещен через массив $ order-> products, прежде чем выполнять раздел «Показать атрибуты продуктов» кода.

код основан на этом фрагменте взяты из checkout_confirmation.php (интернет-магазина):

for ($i=0, $n=sizeof($order->products); $i<$n; $i++) { 
echo '   <tr>' . "\n" . 
'   <td class="infoBoxMargin">' . tep_draw_separator('pixel_trans.gif', '10', '1') . '</td>' . "\n" . 
    '   <td class="main" align="left" valign="top" width="10%">' . $order->products[$i]['qty'] . '&nbsp;x</td>' . "\n" . 
    '   <td class="main" align="left" valign="top" width="60%">' . $order->products[$i]['name']; 

if (STOCK_CHECK == 'true') { 
    echo tep_check_stock($order->products[$i]['id'], $order->products[$i]['qty']); 
} 

if ((isset($order->products[$i]['attributes'])) && (sizeof($order->products[$i]['attributes']) > 0)) { 
    for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) { 
echo '<br /><nobr><small>&nbsp;<i> - ' . $order->products[$i]['attributes'][$j]['option'] . ': ' . $order->products[$i]['attributes'][$j]['value'] . '</i></small></nobr>'; 
    } 
} 

Может кто-нибудь объяснить мне, где дела идут не так?

С наилучшими пожеланиями,

Деннис

+0

Ну с одной стороны Вы пропускаете'} 'где-код в первом образце не будет работать. – Cragmonkey

+1

Почему у вас есть цена, определенная дважды для каждого продукта? – Cragmonkey

+0

@ Gragmonkey. Вы правы насчет отсутствующего '}'. Вы можете добавить это в конце кода. Второй вопрос: массив содержит 2 версии одного и того же продукта (A). Цены в моем примере одинаковы, но могут быть разными. – Dennis

ответ

0

Работа с интернет-магазина кода в течение многих лет я должен сказать, что есть много Wierd кода и, если вы не долго с ним, лучше мигрирующие к чему-то new, thay не использует register_globals, как минимум. Еще одна причина миграции - отсутствие модели MVC - вы всегда видите смешанный PHP-код, html-макет и sql-запросы, особенно в разделе admin. Другой важной причиной миграции является структура таблиц, а точнее, недостатки или неправильные индексы.

Что касается меня, я полностью переписал много кода, включая совершенно новые атрибуты продукта и продуктов. Теперь, например, я использую объект продукта повсюду, включая список продуктов в категории, корзину покупок, список пожеланий и т. Д. Поверьте мне, у меня нет головной боли с отдельными SQL-запросами, которые получают данные разных продуктов.

Теперь вам вопрос. Я полагаю, что проблема здесь:

$data3 = array(); 

Каждый раз, когда вы зацикливаете $ order-> продукты, ваша переменная устанавливается в пустой массив. Поэтому попробуйте определить его до, вы начинаете итерирование $ order-> продуктов. Например:

$data3 = array(); 
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { 
// your code 
} 

и не забудьте удалить $ data3 = array(); из цикла.

Надеюсь, это поможет.

Удачи.

1

Использование данных вашего образца для $order->products, $order->products[$i]['attributes'][$m]['price'] всегда равно нулю. Кроме того, поскольку strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value']) всегда < 50, единственным кодом в разделе //get attribs, который выполняется с вашими данными выборки, является $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value']; ... вот почему $data3[$i][$m][1] - единственное значение, которое заселяется.

Однако, предполагая, что ваши два отсутствующий } принадлежат в конце, то $data3 становится перезаписаны для каждого значения $i на счет $data3 = array(); порога находится.

Если вы переместите $data3 = array(); в начало своего кода (до цикла for), вы, по крайней мере, не будете перезаписывать значения в $ data3 для каждой версии вашего продукта.

Если вы хотите $ Data3 содержать копию каждого атрибута, то попробуйте изменить $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value']; к $data3[$i][$m] = $order->products[$i]['attributes'];

1

@ lazy.lizard

Это может быть так просто ... если вы знаете, что вы делать!

код теперь начинается с: (? Для `for` петли)

$data2=array(); 
$data3 = array(); 

//Show the products information line by line 
$item_count = 0 ; 
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { 

$data2[$i][0] = $order->products[$i]['qty']; 
+1

Если ответ lazy.lizard был полезен, не забудьте его перенести. Если он решит вашу проблему, отметьте ее как принятый ответ. – Cragmonkey