2016-08-01 44 views
0

我試圖根據實體引用字段中的價格字段來計算值。每個用於Drupal數組中的項目的PHP

我現在有這個,它的工作原理...

if (isset($entity->field_choose_a_package['und'][0]['target_id'])) { 
    $package1nid = $entity->field_choose_a_package['und'][0]['target_id']; 
    $package1 = node_load($package1nid); 
    $package1price = $package1->field_price['und'][0]['value']; 
} else { 
    $package1price = 0; 
} 

if (isset($entity->field_choose_a_package['und'][1]['target_id'])) { 
    $package2nid = $entity->field_choose_a_package['und'][1]['target_id']; 
    $package2 = node_load($package2nid); 
    $package2price = $package2->field_price['und'][0]['value']; 
} else { 
    $package2price = 0; 
} 

if (isset($entity->field_choose_a_package['und'][2]['target_id'])) { 
    $package3nid = $entity->field_choose_a_package['und'][2]['target_id']; 
    $package3 = node_load($package3nid); 
    $package3price = $package3->field_price['und'][0]['value']; 
} else { 
    $package3price = 0; 
} 

$packagestotal = $package1price + $package2price + $package3price; 

$entity_field[0]['value'] = $packagestotal; 

然而,有可能是添加包無限量的,而不是我複製代碼20+包,試圖掩蓋我基地,每個循環都必須有一種方法。

我已經試過這樣的事情,

$arr = $entity->field_choose_a_package['und']; 

foreach ($arr as &$value) { 
    if (isset($entity->field_choose_a_package['und'][$value]['target_id'])) { 
     $package1nid = $entity->field_choose_a_package['und'][$value]['target_id']; 
     $package1 = node_load($package1nid); 
     $package1price = $package1->field_price['und'][$value]['value']; 
    } else { 
     $package1price = 0; 
    } 
} 

unset($value); 

,但我不能弄清楚如何遞增的變量,或者甚至需要?我可以從foreach中計算總數嗎?

回答

2
$packagestotal = 0; 
$numPackages = 3; 

for($i = 0; $i <= $numPackages; $i++) { 
    if(isset($entity->field_choose_a_package['und'][$i]['target_id'])) { 
     ${'package' . $i . 'nid'} = $entity->field_choose_a_package['und'][$i]['target_id']; 
     ${'package' . $i} = node_load(${'package' . $i . 'nid'}); 
     $packagestotal += ${'package' . $i}->field_price['und'][0]['value']; 
    } 
} 

$entity_field[0]['value'] = $packagestotal; 

這應該工作。

雖然,我建議你換一個數組包變量,而不是使用variable variables作爲那麼代碼將更具可讀性,你可以使用$package[$i]

+0

那是完美的訪問每個包的屬性,謝謝! – Collins

+0

所以numPackages限制行數?例如,我可以將它設置爲100,以安全地假定沒有人可以訂購(或負擔)超過100個包裹? – Collins

+0

那麼$ numPackages只是說for循環應該迭代多少次。如果$ packages100不存在,則會拋出錯誤。這段代碼假設你提前知道有多少個$ package變量。 – iyop45

相關問題