Jump to content

[SOLVED] help with transforming to multidimensional arrays


tomasd

Recommended Posts

Hi,

I've got 2 arrays that are same size:

print_r ($time);
Array
(
    [0] => 06:30
    [1] => 08:10
    [2] => 09:35
    [3] => 12:00
    [4] => 15:45
    [5] => 17:10
    [6] => 19:35
)

print_r($price);
Array
(
    [0] => 33.44
    [1] => 31.89
    [2] => 56.01
    [3] => 43.12
    [4] => 13.43
    [5] => 19.12
    [6] => 19.91
)

What function do I use to combine both to multidimensional array like so:

Array
        (
            [1] => Array
                (
                    [time] => 06:30
                    [price] => 33.44
                )
        
            [2] => Array
                (
                    [time] => 08:10
                    [price] => 31.89
                )

            [3] => Array
                (
                    [time] => 09:35
                    [price] => 56.01
                )
        ....
        ....
        ....
        )

 

Link to comment
Share on other sites

function combine_time_and_price($time, $price) {
  $result = array();
  $length = count($time); # Assume $price is the same length
  for ($i = 0; $i < $length; $i++) {
    $result[] = array(
      'time' => $time[$i],
      'price' => $price[$i],
    );
  }

  return $result;
}

 

Note that this code will only work if your arrays are indexed with consecutive numbers starting at 0 (which yours are).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.