【问题标题】:What is the most efficient way to merge several php arrays? [closed]合并几个php数组的最有效方法是什么? [关闭]
【发布时间】:2014-04-01 17:56:14
【问题描述】:

我有几个来自表单字段提交的数组,看起来像这样

[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
   )

我需要合并该数据以使其看起来像这样

[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
   ) 

合并这些数据最快/最有效的方法是什么?

更新 根据我的需要稍作修改:

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

【问题讨论】:

标签: php


【解决方案1】:

也许使用 SPL 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);

【讨论】:

  • 这也很有效。非常有趣。
  • 是的,这确实很有趣,而且比我想的要干净得多。
【解决方案2】:
$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]
    );
}

【讨论】:

  • 稍作修改以供我使用,但效果很好 - 谢谢。
猜你喜欢
  • 2020-09-07
  • 1970-01-01
  • 2020-09-13
  • 2023-03-17
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 2010-09-08
相关资源
最近更新 更多