0

I have two simple PHP arrays, like so:

types = ['a', 'b', 'c'];      // 3x1 array
numbers = [1, 2, 3];          // 3x1

What I want is to restructure the data (i.e. transpose + combine them) to be able to loop through them, like this:

result = [['a', 1], ['b', 2], ['c', 3]];    // 3x2

Is there a smart way to achieve this in PHP with some array_XXX native function or do I have to loop over both to manually compose it? Thanks.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
andcl
  • 3,342
  • 7
  • 33
  • 61

3 Answers3

2

If the values in $types are unique, you can do this:

$combined = array_combine($types, $numbers);

This will yield:

[
    'a' => 1,
    'b' => 2,
    'c' => 3,
]

Which you can then iterate over with:

foreach ($combined as $type => $number)

Or just:

foreach (array_combine($types, $numbers) as $type => $number)

If the values in $types are not unique, you can do this:

$combined = array_map(function($a, $b) { return [$a, $b]; }, $types, $numbers);
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • `array_map(function($a, $b) { return [$a, $b]; }, $types, $numbers)` can be [`array_map(null, $types, $numbers)`](https://3v4l.org/j1CjY) – mickmackusa Jun 23 '22 at 22:41
1

It's not perticualy less verbose but the following would avoid you writing a loop:

<?php
$types = ['a', 'b', 'c'];
$numbers = [1, 2, 3];
function map_them($k, $v)
{
    return array($k, $v);
}
$results = array_map('map_them', $types, $numbers);
print_r($results);

output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
        )

    [1] => Array
        (
            [0] => b
            [1] => 2
        )

    [2] => Array
        (
            [0] => c
            [1] => 3
        )

)
sam
  • 164
  • 8
  • You can [replace `'map_them'` with `null`, and not declare the custom function at all](https://3v4l.org/j1CjY). – mickmackusa Jun 23 '22 at 22:40
0

If you create one array of the both, then loop one of the subarrays you can use the key in array_column.

$arr = [$types, $numbers];

foreach($arr[0] as $key => $val){
    $new[] = array_column($arr, $key);
}

var_dump($new);

Output

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    int(1)
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "b"
    [1]=>
    int(2)
  }
  [2]=>
  array(2) {
    [0]=>
    string(1) "c"
    [1]=>
    int(3)
  }

https://3v4l.org/QWOJg

Andreas
  • 23,610
  • 6
  • 30
  • 62