1

I'm using the array_column function to convert a 3d array into new arrays with the values.

I have multiple columns that all need to be converted in an array. Is there an easier or cleaner way to do this?

Instead of doing this:

$levels = array_column($arr, 'level');
$times = array_column($arr, 'time');
$numbers = array_column($arr, 'number');

Here's an example of my array:

$arr = [
    [
        'level' => 0,
        'time' => 3,
        'number' => 5
    ],
    [
        'level' => 1,
        'time' => 4,
        'number' => 3
    ],
];
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jonas de Herdt
  • 422
  • 5
  • 18

1 Answers1

1

I think the simplest way to do this is with a nested loop.

foreach($arr as $inner) {
    foreach($inner as $key => $value) {
        $columns[$key][] = $value;
    }
}

This will produce a result like this:

[
   'level' => [0, 1],
   'time' => [3, 4],
   'number' => [5, 3]
]

If you really want to create separate variables like the example in your question, you can use variable variables for that. I would advise against it, but here's an example of that.

foreach($arr as $inner) {
    foreach($inner as $key => $value) {
        $$key[] = $value;
    }
}

Dynamically creating variables like that is risky. You can inadvertently overwrite other variables if one of the column names happens to be the same. Using the first method will contain the result in one predictable place, and $columns['level'] can be used in the following code just the same as a separate $level variable would.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80