【发布时间】:2016-08-28 10:02:00
【问题描述】:
我有一系列这样的产品:
$rows = [
100 => [
['product_id' => 101, 'name' => ''],
['product_id' => 102, 'name' => ''],
['product_id' => 103, 'name' => ''],
],
200 => [
['product_id' => 201, 'name' => ''],
['product_id' => 202, 'name' => ''],
],
300 => [
['product_id' => 301, 'name' => ''],
['product_id' => 302, 'name' => ''],
['product_id' => 303, 'name' => ''],
['product_id' => 304, 'name' => ''],
]
];
我想把它转换成这样的结构,去除一层深度:
$rows = [
['product_id' => 101, 'name' => ''], //1st from 100 subArray
['product_id' => 201, 'name' => ''], //1st from 200 subArray
['product_id' => 301, 'name' => ''], //1st from 300 subArray
['product_id' => 102, 'name' => ''], //2nd from 100 subArray
['product_id' => 202, 'name' => ''], //etc...
['product_id' => 302, 'name' => ''],
['product_id' => 103, 'name' => ''],
['product_id' => 303, 'name' => ''],
['product_id' => 304, 'name' => ''],
];
现在我正在尝试使用此代码:
$max_store_products = max(array_map('count', $rows));
$sortedArray = array();
for($j = 0; $j < $max_store_products; $j++)
{
foreach($rows as $store_id => $store_products)
{
$sp = $rows[$store_id][$j];
if(isset($sp))
{
$sortedArray[] = $rows[$store_id][$j];
}
else
unset($rows[$store_id]);
}
}
但这确实需要很长时间,也没有给我想要的预期输出。
有没有更简单的方法来做到这一点?
【问题讨论】:
标签: php arrays multidimensional-array transpose