I have an array of products like this:
$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]);
}
}
但这样做很费时间,并且也没有给我期望的输出结果。是否有更简单的方法?