PHP从多维数组和单数组循环创建新数组

时间:2016-05-06 05:42:17

标签: php arrays multidimensional-array

我有一个多维数组和一个数组,我想用每个数组中的键作为标记点来创建包含这些数组数据的新数组。

单一阵列:

array(12) {
  [11]=>
  string(18) "Blacklist Customer"
  [2]=>
  string(11) "Change Mind"
  [8]=>
  string(5) "Fraud"
  [1]=>
  string(13) "Late Delivery"
  [0]=>
  string(3) "N/A"
  [7]=>
  string(12) "No Statement"
  [5]=>
  string(8) "No Stock"
  [4]=>
  string(15) "Order Suspected"
  [10]=>
  string(20) "SOP Cancelation Rule"
  [9]=>
  string(15) "Sourcing Issues"
  [3]=>
  string(13) "Suspect Fraud"
  [6]=>
  string(20) "Wrong Payment Method"
}

多维数组:

array(6) {
  [1]=> //Late delivery
  array(2) {
    [0]=> // this is sales key. It means sales with ID 0 have 4 late delivery
    float(4)
    [2]=> // this is sales key. It means sales with ID 2 have 3 late delivery
    float(3)
  }
  [0]=> //NA
  array(2) {
    [0]=>
    float(2)
    [2]=>
    float(10)
  }
  [2]=> //Change Mind
  array(2) {
    [0]=>
    float(1)
    [2]=>
    float(1)
  }
  [5]=> //No stock
  array(1) {
    [2]=>
    float(1)
  }
  [4]=> //Order Suspected
  array(1) {
    [2]=>
    float(1)
  }
  [6]=> //Wrong payment method
  array(1) {
    [10]=>
    float(1)
  }
}

我希望有这样的新数组(我使用键来指示我将推送哪些数据或添加到新数组。:

array(12) {
  [Blacklist Customer]=>
  array(0) {
  }
  [Change Mind]=>
  array(2) {
    [0]=>
    float(1)
    [2]=>
    float(1)
  }
  [Fraud]=>
  array(0) {
  }
  [Late Delivery]=>
  array(2) {
    [0]=>
    float(4)
    [2]=>
    float(3)
  }
  [N/A]=>
  array(2) {
    [0]=>
    float(2)
    [2]=>
    float(10)
  }
  [No Statement]=>
  array(0) {
  }
  [No Stock]=>
  array(1) {
    [2]=>
    float(1)
  }
  [Order Suspected]=>
  array(1) {
    [2]=>
    float(1)
  }
  [SOP Cancelation Rule]=>
  array(0) {
  }
  [Sourcing Issues]=>
  array(0) {
  }
  [Suspect Fraud]=>
  array(0) {
  }
  [Wrong Payment Method]=>
  array(1) {
    [10]=>
    float(1)
  }
}

是否可以使用循环创建新的数组? 非常感谢你!

1 个答案:

答案 0 :(得分:1)

此代码:

$arr; // Array
$mult; // Multi dimensional array
$out; // created array

foreach ( $arr as $id=>$name ) {
    if ( array_key_exists($mult, $id) ) 
       $out[$name] = $mult[$id];
    else
       $out[$name] = array();
}