Collins
Collins

Reputation: 1149

PHP for each for items in array with Drupal

I am trying to calculate a value based on a price field in an entity reference field.

I currently have this, which works...

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;

However, there could be an unlimited amount of packages added, and rather than me replicate the code for 20+ packages to try and cover my bases, there must be a way I can do a for each loop.

I have tried something like this,

$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);

but I cant figure out how to increment the variables, or if even need to? Can i just calculate the totals from the foreach?

Upvotes: 0

Views: 44

Answers (1)

Roy
Roy

Reputation: 3267

$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;

That should work.

Although, I would recommend that you wrap the package variables in an array rather than using variable variables as then the code would be much more readable and you could access each package attribute using $package[$i]

Upvotes: 2

Related Questions