1

I have a PHP array that I am trying to split into 2 different arrays into that particular array. I am trying to pull out any values for each "destination" and "balance".

Here is the array i get,

Array
(
    [destination_1] => 1
    [balance_1] => 1
    [destination_2] => 2
    [balance_2] => 2
    [destination_3] => 3
    [balance_3] => 3
)

I need output like,

Array  ( 
[0] => Array ( 
             [destination_1] => 1 
             [balance_1] => 1
             ) 
[1] => Array ( 
             [destination_2] => 2 
             [balance_1] => 2
             )   
[2] => Array (
             [destination_3] => 3
             [balance_3] => 3
             )
    ) 
3
  • What have you tried? A simple foreach loop with a counter seems a possibility. Commented Jul 14, 2020 at 13:47
  • I am trying.. Post what you are trying and what is not working Commented Jul 14, 2020 at 13:47
  • @B001ᛦ I've tried array_walk and array_chunk. but seems like none is helping in this. Commented Jul 14, 2020 at 13:53

1 Answer 1

2

What you need is array_chunk()

$arr = [
    "destination_1" => 1,
    "balance_1" => 1,
    "destination_2" => 2,
    "balance_2" => 2,
    "destination_3" => 3,
    "balance_3" => 3
];

$result =  array_chunk($arr, 2, true); 

Output:

Array
(
    [0] => Array
        (
            [destination_1] => 1
            [balance_1] => 1
        )

    [1] => Array
        (
            [destination_2] => 2
            [balance_2] => 2
        )

    [2] => Array
        (
            [destination_3] => 3
            [balance_3] => 3
        )

)
Sign up to request clarification or add additional context in comments.

Comments

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.