使用预定义的键转置 PHP 多维数组 [英] Transpose a PHP multidimensional array with predefined keys
本文介绍了使用预定义的键转置 PHP 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有 3 个键(长度"、宽度"和高度")的多维数组.每个键都与一个值数组相关联:
I have a multidimensional array with 3 keys ("length", "width" and "height). Each key is associated with an array of values:
$data = [
"length" => ["12", "44"],
"width" => ["22", "45"],
"height" => ["22", "34"]
];
如何将每个键的列转换为 3 列的行,如下所示:
How can I transpose the columns of each key into rows of 3 columns as follows:
$rows = [
["length" => "12", "width" => "22", "height" => "22"],
["length" => "44", "width" => "45", "height" => "34"]
];
推荐答案
以下函数将完成这项工作:
The following function will do the job:
function transpose($data)
{
$result = [];
$keys = array_keys($data);
for ($row = 0, $rows = count(reset($data)); $row < $rows; $row++) {
foreach ($keys as $key) {
$result[$row][$key] = $data[$key][$row];
}
}
return $result;
}
请注意,该函数是一个通用解决方案,它不依赖于键的名称,也不依赖于每个键的条目数.
Notice that the function is a general solution it doesn’t depend on the name of the keys nor on the number of entries of each key.
这篇关于使用预定义的键转置 PHP 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文