Rearrange an array with multiple keys

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 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 made many array functions, but still stuck to this.

+6
source share
3 answers

If the set of fields remains the same as:

  • Currency
  • Buy value
  • Sale 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] ); } 
+5
source

Demo


 $data = array ( 'USD', '10150.00', '9850.00', 'SGD', '8015.40', '7915.40', 'HKD', '1304.60', '1288.60', ); $result = array(); while (is_null($value = array_shift($data)) !== true) { if (preg_match('~^[AZ]{3}$~', $value) > 0) { $result[$value] = array ( 'Buy' => array_shift($data), 'Sell' => array_shift($data), ); } } print_r($result); // transformed array 
+2
source

If I can trust the structural structure of your input array, I can provide a smooth single line (no loops for / while) for you ...

 $input=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" ); array_map(function($a)use(&$output){$output[$a[0]]=["Buy"=>$a[1],"Sell"=>$a[2]];},array_chunk($input,3)); var_export($output); 

Output:

 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', ), ) 

Here is a breakdown of my array_map () using array_chunk () :

 array_map( // iterate each subarray from array_chunk() function($a) // $a = each subarray use(&$output){ // declare the output array as modifiable $output[$a[0]]= // use 1st subarray value as key ["Buy"=>$a[1], // use 2nd subarray value as Buy value "Sell"=>$a[2]]; // use 3rd subarray value as Sell value }, array_chunk($input,3) // feed in an array of 3-element subarrays ); 

Later editing (I thought I would reset the function variable, which would also give the same result):

 array_map(function($K,$B,$S)use(&$output){$output[$K]=["Buy"=>$B,"Sell"=>$S];},...array_chunk($input,3)); 

By the way, both methods with the same layer have the same character length, so I believe that it depends on personal preferences.

0
source

Source: https://habr.com/ru/post/949375/


All Articles