jimshot
jimshot

Reputation: 109

Converting Non Linear Numeric PHP Array Indexes to Array Values

I have an array comprising months (keys) and values See shortened example below. It is being generated by a legacy client system so I can only manipulate what I am presented with (not ideal).

$cost_data= array
            (
                [9] => 1110
                [10] => 111
                [8] => 100
                [7] => 200
                [6] => 690
                [11] => 222
            )

Note-the non linear keys represent months of the year.

I need to change the data structure to the format below and am not having much luck after several hours of trying different approaches and searching.

   $cost_data = array
   (
     array("9",1110),
     array("10",111),
     array("8",100),
     array("7",200),
     array("6",690),
     array("11",222)
    );  

Is there a simple built in function or does anyone know a neat method for achieving this transformation?

Upvotes: 0

Views: 48

Answers (2)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Here is my go.

<?php
$cost_data= [
    9 => 1110,
    10 => 111,
    8 => 100,
    7 => 200,
    6 => 690,
    11 => 222,
];

asort($cost_data);  //sort

array_walk($cost_data,function(&$v,$k){
    $v = [$k,$v];
});

print_r(array_values($cost_data));

Outputs ( after some cleanup):

array (
  0 => array(9,1110),
  1 => array(10,111),
  2 => array(8,100),
  3 => array(7,200),
  4 => array(6,690),
  5 => array(11,222)
)

You can test it here.

http://sandbox.onlinephpfunctions.com/code/95557489eb19e9e34c55abef71accd1219682350

If you don't care about the keys, you can skip the array_values which resets the numeric indexes, and save a bit on performance. Without the array_values it looks like this

array (
  9 => array(9,1110),
  10 => array(10,111),
  8 => array(8,100),
  7 => array(7,200),
  6 => array(6,690),
  11 => array(11,222)
)

So, like I said you can save a tiny bit on performance by leaving it out. I didn't measure it but I would wager it's a bit faster then array_map, as it does pass by reference.

update

I timed both the array_map and mine array_walk. And for 30k iterations

Array Walk Time: 0.045436
Array Map Time: 0.047619 

I would say their is no significant difference between the two.

Upvotes: 1

pumbo
pumbo

Reputation: 3826

$cost_data = array(
    9 => 1110,
    10 => 111,
    8 => 100,
    7 => 200,
    6 => 690,
    11 => 222
);


$converted = array_map(function($k, $v) { return array($k, $v); }, array_keys($cost_data), $cost_data);

Upvotes: 1

Related Questions