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

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.