将数组转换为多维数组

问题描述 投票:0回答:2

我正在使用这种数组

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

我想要的输出应该是这样的

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

请有人帮助我。

php arrays laravel multidimensional-array
2个回答
0
投票

你应该像这样编写自己的函数:

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);

0
投票

这里是使用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));

输出将是:

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

有关演示,请参阅:https://3v4l.org/msjJs

© www.soinside.com 2019 - 2024. All rights reserved.