简体   繁体   中英

PHP Create new array from multidimensional array and single array looping

I have a multidimensional array and an array, I want to create new array with data from these array using keys from each array as mark point.

Single 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"
}

Multidimensional array:

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

And I want to have new array like this (I'm using the keys to indicate which data will I push or add to the new array.:

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

Is it possible to have new array like that using looping? Thank you so much!

This code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM