我正在尝试根据“product_type”重新排列我的数组。 结果中索引“product_type”的每第 4 个位置应该是“manufacturer”。
如果“卖家”条目太少,则“制造商”条目可能存在于下一个可用位置(反之亦然)。
我目前的输入是这样的:
$arr1 = array(
0 => ['product_type'=>'manufacturer','id'=>1],
1 => ['product_type'=>'manufacturer','id'=>2],
2 => ['product_type'=>'seller'],
3 => ['product_type'=>'seller'],
4 => ['product_type'=>'seller'],
5 => ['product_type'=>'seller'],
6 => ['product_type'=>'seller'],
7 => ['product_type'=>'manufacturer','id'=>3],
);
我期望的新数组应该是这样的:
Array(
[0] => Array
(
[product_type] => seller
)
[1] => Array
(
[product_type] => seller
)
[2] => Array
(
[product_type] => seller
)
[3] => Array
(
[product_type] => manufacturer
[id] => 1
)
[4] => Array
(
[product_type] => seller
)
[5] => Array
(
[product_type] => seller
)
[6] => Array
(
[product_type] => manufacturer
[id] => 2
)
[7] => Array
(
[product_type] => manufacturer
[id] => 3
)
)
对于这个解决方案,我正在尝试这个,但在第一个位置的结果中我得到了“制造商”产品。
$arr1 = array(
0 => ['product_type'=>'manufacturer','id'=>1],
1 => ['product_type'=>'manufacturer','id'=>2],
2 => ['product_type'=>'seller'],
3 => ['product_type'=>'seller'],
4 => ['product_type'=>'seller'],
5 => ['product_type'=>'seller'],
6 => ['product_type'=>'seller'],
7 => ['product_type'=>'manufacturer','id'=>3],
) ;
function rearrange(&$arr, $n)
{
for ($i = 0; $i < $n; $i++)
{
$j = $i+1;
if($arr[$i]['product_type'] =='manufacturer'){
if($j%4!= 0){
//echo $i;
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
} else {
if ($i==0 || $i==1 || $i==2) {
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
} else {
$temp = $arr[$i];
$arr[$i] = $temp;
}
}
} else {
$temp = $arr[$i];
$arr[$i] = $temp;
}
}
return $arr;
}
$keys = array_keys ($arr1);
$n = count ($keys);
$arr = rearrange($arr1, $n);
print_r($arr);
最佳答案
- 在您迭代时,每隔 4 个键存储一次制造商条目。
- 在不是每 4 个 key 的每个 key 处存储卖家条目。
- 对新分配的键进行排序。
- 重新索引数组。
只要您有足够的符合条件的数据,您的模式就会得到支持。当一组数据太多时,它就会在最后集中在一起。
代码:(Demo)
$arr1 = array(
0 => ['product_type'=>'manufacturer','id'=>1],
1 => ['product_type'=>'manufacturer','id'=>2],
2 => ['product_type'=>'seller'],
3 => ['product_type'=>'seller'],
4 => ['product_type'=>'seller'],
5 => ['product_type'=>'seller'],
6 => ['product_type'=>'seller'],
7 => ['product_type'=>'manufacturer','id'=>3],
);
$manuCounter = 0;
$sellerCounter = 0;
$result = [];
foreach ($arr1 as $row) {
if ($row['product_type'] === 'manufacturer') {
$manuCounter += 4;
$result[$manuCounter] = $row;
} else {
++$sellerCounter;
if (!($sellerCounter % 4)) {
++$sellerCounter;
}
$result[$sellerCounter] = $row;
}
}
ksort($result);
var_export(array_values($result));
关于php - 重新排序多维数组,以便每 4 行出现具有特定列值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65103432/