Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange array with multiple keys

Tags:

arrays

php

I have an array:

Array
(
    [12] => USD
    [13] => 10150.00
    [14] => 9850.00
    [15] => SGD
    [16] => 8015.40
    [17] => 7915.40
    [18] => HKD
    [19] => 1304.60
    [20] => 1288.60
    ...
)

What I want to do is arrange it to be like this:

Array
(
    [USD] => Array
             (
                 [Buy] => 10150.00
                 [Sell] => 9850.00
             )
    [SGD] => Array
             (
                 [Buy] => 8015.40
                 [Sell] => 7915.40
             )
    [HKD] => Array
             (
                 [Buy] => 1304.60
                 [Sell] => 1288.60
             )
    ...
)

I've done a lot of array functions but still stuck with this.

like image 909
frozenade Avatar asked Jul 13 '13 16:07

frozenade


1 Answers

If the suite of fields remains the same as:

  1. Currency
  2. Buy value
  3. Sell value

then, you can do:

$old_array = array('USD', 123.00, 432.34, 'SGD', 421.41, 111.11);
$new_array = array();

for ($i = 0; $i < count($old_array); $i = $i + 3) {
    $new_array[$old_array[$i]] = array
    (
        'Buy' => $old_array[$i + 1],
        'Sell' => $old_array[$i + 2]
    );
}
like image 168
Stéphane Bruckert Avatar answered Sep 22 '22 13:09

Stéphane Bruckert