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.