Home > OS >  Convert array to Multi dimensional array
Convert array to Multi dimensional array

Time:11-05

I am using this kind of array

array[
    0 => 'top left',
    1 => 'top right',
];
array[
    0 => 'Switch Up',
    1 => 'Switch Down',
];

My desired output should be like

    array[
        0 => 'top left',
        1 => 'Switch Up',
    ];
    array[
        0 => 'top right',
        1 => 'Switch Down',
    ];

Some one please help me.

CodePudding user response:

You should write your own function like that:

Inputs:

$alignments = [
    'top left',
    'top right',
];

$switches = [
    'Switch Up',
    'Switch Down',
];
$result = [];

foreach ($alignments as $index => $alignment) {
    $result[] = [
        'alignment' => $alignment,
        'switches' => $switches[$index] ?? null,
    ];
}

print_r($result);

CodePudding user response:

Here's an example of the use of array_column():

$alignments = [
    'top left',
    'top right',
];

$switches = [
    'Switch Up',
    'Switch Down',
];

$combined = [$alignments, $switches];

var_export(array_column($combined, 0));
var_export(array_column($combined, 1));

The output would be:

array (
  0 => 'top left',
  1 => 'Switch Up',
)
array (
  0 => 'top right',
  1 => 'Switch Down',
)

For a demo see: https://3v4l.org/msjJs

This solution is not self-evident, if you're unfamiliar with it.

The $combined array is 2-dimensional, and looks like this:

array (
  0 => array (
    0 => 'top left',
    1 => 'top right',
  ),
  1 => array (
    0 => 'Switch Up',
    1 => 'Switch Down',
  ),
)

With array_column($combined, 0) you get all the values with the zero keys from the nested arrays. With array_column($combined, 1) you get all values with key = 1.

CodePudding user response:

$first = [
    0 => 'top left',
    1 => 'top right',
];

$last = [
    0 => 'Switch Up',
    1 => 'Switch Down',
];

$export = array_map(null, $first, $last);

#sort method
  • Related