0

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!

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! it worked! Except the parameter of array_key_exist is reversed. Thank again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.