2017-01-05 4 views
1

if 문을 두 번 완료하는 데 어려움이 있습니다. 나머지는 잘 작동하지만 다른 하위 배열을 체크인하려고하면 작동하지 않습니다.PHP 배열 : for :

편집 : - 조건이 크기 속성을 확인하는 경우, 둘째 - 조건이 제품 의 종류를 확인하는 경우 첫 번째. - 제품 : sweatshirt_crianca 및 sweatshirtc_crianca_capuz - 크기 : 4_anos, 6_anos, 8_anos, 11_anos, 12_anos 및 14_anos 해제해야합니다 ($ this-> enabled = false;) 14_anos를 제외한 크기입니다.

이 내가 $ 순서 -> 제품 [$ i]를

Array 
(
    [qty] => 1 
    [name] => .Mr Mickey T-shirt 
    [model] => 
    [image] => blusa-mr-mrs-blusao-sweat-camisolas-portugal.png 
    [tax] => 20 
    [tax_description] => IVA 23% 
    [price] => 10.8333 
    [final_price] => 16.6666 
    [weight] => 0.00 
    [id] => 1342{18}135{17}132{19}148 
    [attributes] => Array 
     (
      [0] => Array 
       (
        [option] => s_cor_produto 
        [value] => branco 
        [option_id] => 18 
        [value_id] => 135 
        [prefix] => + 
        [price] => 0.0000 
       ) 

      [1] => Array 
       (
        [option] => s_produto 
        [value] => sweatshirt_crianca 
        [option_id] => 17 
        [value_id] => 132 
        [prefix] => + 
        [price] => 5.8333 
       ) 

      [2] => Array 
       (
        [option] => s_tamanho_produto 
        [value] => 8_anos 
        [option_id] => 19 
        [value_id] => 148 
        [prefix] => + 
        [price] => 0.0000 
       ) 

     ) 

) 
Array 
(
    [qty] => 1 
    [name] => Adivinha quem vai ser mama shirt 
    [model] => 
    [image] => adivinha-quem-vai-ser-mama-tshirt-gravida.png 
    [tax] => 20 
    [tax_description] => IVA 23% 
    [price] => 10.8333 
    [final_price] => 10.8333 
    [weight] => 0.00 
    [id] => 1860{20}157{18}139{17}128{19}152 
    [attributes] => Array 
     (
      [0] => Array 
       (
        [option] => s_cor_impressao 
        [value] => branco 
        [option_id] => 20 
        [value_id] => 157 
        [prefix] => + 
        [price] => 0.0000 
       ) 

      [1] => Array 
       (
        [option] => s_cor_produto 
        [value] => azul_royal 
        [option_id] => 18 
        [value_id] => 139 
        [prefix] => + 
        [price] => 0.0000 
       ) 

      [2] => Array 
       (
        [option] => s_produto 
        [value] => tshirt_mulher 
        [option_id] => 17 
        [value_id] => 128 
        [prefix] => + 
        [price] => 0.0000 
       ) 

      [3] => Array 
       (
        [option] => s_tamanho_produto 
        [value] => M 
        [option_id] => 19 
        [value_id] => 152 
        [prefix] => + 
        [price] => 0.0000 
       ) 

     ) 

) 

때때로 할 수있는 1 개 또는 4 하위 어레이를 포함에서 무엇을 얻을 수 있습니다. 이것은 osCommerce의 대구 지불입니다. 나는이 속성의 속성에 따라이 메소드에서 특정 제품을 제외하려고합니다. [값]을 확인하는 첫 번째 if 문에서 올바르게 작동하지만 구문에 주석이있는 행은 정확하지만 작동하지 않습니다. 이것은 내가 가지고있는 코드입니다 :

for ($i=0, $n=sizeof($order->products); $i<$n; $i++) { 
    if ($order->products[$i]['weight'] > '0.00') { 
     $this->enabled = false; 
    } 
    if ((isset($order->products[$i]['attributes'])) && (sizeof($order->products[$i]['attributes']) > 0)) { 
     for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) { 
     if (($order->products[$i]['attributes'][$j]['option'] == 's_produto') && ($order->products[$i]['attributes'][$j]['value'] == 'sweatshirt_crianca')) { 
      //if (($order->products[$i]['attributes'][$j]['option'] == 's_tamanho_produto') && ($order->products[$i]['attributes'][$j]['value'] == '14_anos')) { 
      $this->enabled = false; 
      //} 
     } 
     else if (($order->products[$i]['attributes'][$j]['option'] == 's_produto') && ($order->products[$i]['attributes'][$j]['value'] == 'sweatshirtc_crianca_capuz')) { 
      //if (($order->products[$i]['attributes'][$j]['option'] == 's_tamanho_produto') && ($order->products[$i]['attributes'][$j]['value'] != '14_anos')) { 
      $this->enabled = false; 
      //} 
     } 
     } 
    } 
    } 

모든 솔루션? 감사.

+0

는 그 주석'if's은 다른 사람 안에 있어야하고 있습니까? A = B인지 테스트 중이니까. 그렇다면 A = C인지 테스트합니다. 물론 그렇지 않습니다. – sidyll

+0

글쎄,이 속성들 중 어느 것도이 두 조건을 모두 통과하지 못하는 것 같습니다 (한 번 주석 처리되지 않은 상태). 네가 가지고있는 것처럼 그들이 중첩되어 있다고 확신합니까? – segFault

+0

논리가 의미가 없습니다. 어쩌면 우리가 당신의 논리를 의사 코드로 제공하여 우리가 무엇을 성취하려고하는지 알 수 있습니다. – CodeGodie

답변

0

Sidyll는 나를 이길하지만 비슷한 라인을 따라 생각하고 있었다 :

// loop through each product 
    foreach ($order->products as $prod) 
    { 

     if($prod['weight'] > '0.00') 
     { 
       $this->enabled = false; 
     } 

     if(isset($prod['attributes']) && is_array($prod['attributes'])) 
     { 
       $matching_product_type_found = false; 
       $matching_valid_size_found = false; 

       foreach ($prod['attributes'] as $attr) 
       { 
         if ($attr['option'] == 's_produto' && 
          ($attr['value'] == 'sweatshirt_crianca' || 
           $attr['value'] == 'sweatshirtc_crianca_capuz' 
          )) 
          { 
          $matching_product_type_found = true; 
          } 

         if ($attr['option'] == 's_tamanho_produto' && $attr['value'] == '14_anos') 
          { 
          $matching_valid_size_found = true; 
          } 
       } 


       if($matching_product_type_found == true) 
       { 

        $this->enabled = $matching_valid_size_found; 

       } 

     } 

    } 
+0

작동하지 않을 수 있습니다. 다른 매개 변수로 전환, 다른 매개 변수를 가지고, 나는 [옵션] => s_produto [옵션] => s_tamanho_produto [값] = 아닌지 확인하는 사이를 전환했습니다 14_anos – sinopia

0

내가 덜 오류에 더 읽기 및 경향 수 있도록 foreach를 사용하여 루프를 다시 작성합니다. 또한 귀하의 비교를 위해 (=====) 조심하십시오. 이 방법을 시도해보십시오

foreach ($order->products as $product) { 
    if ($product['weight'] > 0.00) { 
     $this->enabled = false; 
    } 
    if (!empty($product['attributes'])) { 
     foreach ($product['attributes'] as $attribute) { 

      if ($attribute['option'] === 's_produto') { 

       switch ($attribute['value']) { 
        case "sweatshirt_crianca" : 
         // .. do some code 
         break; 
        case "s_tamanho_produto" : 
         // .. do some code 
         break; 
        case "14_anos" : 
         // .. do some code 
         break; 
        case "something else" : 
         // .. do some code 
         break; 
        default: 
         break; 
       } 

      } 
     } 
    } 
} 
+0

s_tamanho_produto가 $ order-> 제품 [$ i] [ 'attributes'] [$ j] [ 'option'] – sinopia

1

코드의 주된 문제는 서로 다른 배열 요소를 테스트하고 싶지만 하나 하나를 반복하는 동안 당신이 그것을하고있는 것입니다. 코드 안에 for 루프는 반복의 현재 요소 만 볼 수 있습니다. 따라서 if 문을 중첩 할 때는 기본적으로 테스트입니다. 현재 요소가 무엇인가와 동일한 경우, 그리고 이 동일한 요소가 다른 것과 동일하면 테스트 할 것입니다. 이 논리가 실패합니다.

분명히 optionvalue 키가 중요하기 때문에 나는 을 먼저 사용하여 다른 배열을 만드는 것이 좋습니다. 그런 다음 반복자 내에 현재 속성 뿐 아니라 이러한 모든 속성을 한 번에 에 액세스 할 수 있습니다. 예를 들어, 여기에 문제의 마지막 예를 들어 간단한 속성 배열 입니다 :

$attributes = [ 
    s_cor_impressao => 'branco' 
    s_cor_produto  => 'azul_royal' 
    s_produto   => 'tshirt_mulher' 
    s_tamanho_produto => 'M' 
]; 

이 코드를 단순화하기 쉽게 이것을 만들려면, 나는 foreach ... as 루프를 사용하는 것이 좋습니다. 또한 배열에 항목이 있는지 확인하지 않아도됩니다. 항목이없는 경우 foreach은 이 전혀 실행되지 않습니다. 을 미리 알지 못하면 설정 한 것과 같은지 확인해 볼 가치가 있습니다.그러나 또 다른 방법은 continue 컨트롤 구조로 설정되지 않은 경우 다음 반복에서 직접 으로 건너 뛰는 것입니다. 이 같은 테스트를 할 수있는 위의 테스트 마크에서 지금

foreach ($order->products as $product) { 
    if ($product['weight'] > 0) 
     $this->enabled = false; 

    if (!isset($product['attributes']) || !is_array($product['attributes'])) 
     continue; 

    $attributes = []; 
    foreach ($products['attributes'] as $attr) 
     $attributes[ $attr['option'] ] = $attr['value']; 

    # [tests] 
} 

:

if ($attr['s_produto'] == 'sweatshirt_crianca' && 
    $attr['s_tamanho_produto'] == '14_anos') { 
    # do something 
    # $this->enabled = false; 
} else if (...) { 
    # do something else 
}