-1

I want to convert this multidimensional array:

array(
[0] => array (
   "interest_income-bank" => "520.541"
   "total_interest_expense" => "145.791"
   "net_interest_income" => "434.937"
   "loan_loss_provision" => "135.664"
   .
   .
)
[1] => array (
   "interest_income-bank" => "617.894"
   "total_interest_expense" => "205.508"
   "net_interest_income" => "506.510"
   "loan_loss_provision" => "120.586"
   .
   .    
)
)

to an array like this:

array(
[interest_income-bank] => array (
   "0" => "520.541"
   "1" => "617.894"
   .
   .
)
[total_interest_expense] => array (
   "1" => "145.791"
   "2" => "205.508"
   .
   .
)
)

Tried a lot with no luck :(

Any help would be much appreciated!

0

2 Answers 2

6

Iterate the outer array, then the inner arrays. Add each value to an indexed array in your result.

foreach ($your_array as $sub_array) {
    foreach ($sub_array as $key => $value) {
        $result[$key][] = $value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You actually don't have to iterate the full array, you only need to iterate one subarray and use array_column to grab all values in the full array.

Foreach($arr[0] as $key => $val){
    $res[$key] = array_column($arr, $key);
}

See it here: https://3v4l.org/SAZJd

If the array is larger than what you showed here (your dots suggest that I think).
This method will be much much faster than looping every single value of the array.

1 Comment

just love array_column() - remember it was introduced in php 5.5

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.