0

I have several arrays from form field submissions that look like this

[budget_type_id] => Array
   (
      [0] => 1
      [1] => 2
      [2] => 2
      [3] => 5
   )

[budget_f1] => Array
   (
      [0] => 100
      [1] => 200
      [2] => 300
      [3] => 400
   )

[budget_f2] => Array
   (
      [0] => 100
      [1] => 200
      [2] => 300
      [3] => 400
   )

I need to merge that data to look like this

[arr1] => Array
   (
      [budget_type_id] => 1
      [budget_f1] => 100
      [budget_f2] => 100
   )
[arr2] => Array
   (
      [budget_type_id] => 2
      [budget_f1] => 200
      [budget_f2] => 200
   )

[arr3] => Array
   (
      [budget_type_id] => 2
      [budget_f1] => 300
      [budget_f2] => 300
   )
[arr4] => Array
   (
      [budget_type_id] => 5
      [budget_f1] => 400
      [budget_f2] => 400
   ) 

What is the quickest/most efficient way to merge this data?

UPDATE Modified slightly for my needs:

$contractBudgets = array();

for($i = 0 ; $i < count($formfields['budget_type_id']) ; $i++){

    $newBudget = $this->modx->newObject('ContractBudget');

    $newBudget->set('budget_type_id',$formfields['budget_type_id'][$i]);    
    $newBudget->set('budget_f1',$formfields['budget_f1'][$i]);  
    $newBudget->set('budget_f2',$formfields['budget_f2'][$i]);  

    $contractBudgets[] = $newBudget;
}

$newContract->addMany($contractBudgets);
5
  • 2
    I know this has been asked here before. Commented Feb 28, 2014 at 16:08
  • A foreach() loop is very efficient Commented Feb 28, 2014 at 16:11
  • stackoverflow.com/questions/8561987/php-merge-two-arrays Commented Feb 28, 2014 at 16:11
  • Why not change the form to submit as you want it? Commented Feb 28, 2014 at 16:29
  • @AbraCadaver - the form dynamically generates groups of budget types. Commented Feb 28, 2014 at 17:54

2 Answers 2

3

Perhaps using SPLs MultipleIterator

$budget_type_id = array( 1, 2, 2, 5, );
$budget_f1 = array( 100, 200, 300, 400, );
$budget_f2 = array( 100, 200, 300, 400, );

$mi = new MultipleIterator(multipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($budget_type_id), 'budget_type_id');
$mi->attachIterator(new ArrayIterator($budget_f1), 'budget_f1');
$mi->attachIterator(new ArrayIterator($budget_f2), 'budget_f2');

$newArray = array();
foreach($mi as $details) {
    $newArray[] = $details;
}

var_dump($newArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this indeed is interesting, and much cleaner than my answer I think.
0
$merged = array();
for($i = 0 ; $i < count($budget_type_id) ; $i++){
    $merged[] = array(
        'budget_type_id'=>$budget_type_id[$i], 
        'budget_f1' => $budget_f1[$i],
        'budget_f2' => $budget_f2[$i]
    );
}

1 Comment

Slightly modified for my use, but works great - thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.