我有一个看起来像这样的数组,
Array
(
[email_address] => Array
(
[0] => sadasdasd
[1] => Simosdsad
)
[firstname] => Array
(
[0] => sadsadas
[1] => simon
)
[surname] => Array
(
[0] => asdasdasdasdasd
[1] => ainley
)
[companies_company_id] =>
[save_user] => Save User
)
所有键 [0] 都是相关的,是否可以将它们制作成自己的数组?
一个简单的方法是这样的:
$newArray = array();
foreach($array as $key => $value) {
$newArray[] = $value[0];
}
你有什么理由不这样做吗?
要转置输入数组的列数据,请使用嵌套循环,仅在遇到子数组时才输入该循环。 结果数组声明只会将第一级键与第二级键交换——这避免了声明单个数组变量的笨拙。 演示
$result = [];
foreach ($array as $k => $row) {
if (is_array($row)) {
foreach ($row as $i => $v) {
$result[$i][$k] = $v;
}
}
}
var_export($result);
输出:
array (
0 =>
array (
'email_address' => 'sadasdasd',
'firstname' => 'sadsadas',
'surname' => 'asdasdasdasdasd',
),
1 =>
array (
'email_address' => 'Simosdsad',
'firstname' => 'simon',
'surname' => 'ainley',
),
)