gpt4 book ai didi

php - 如何将一个数组重新分配到某个 "shape"的另一个数组中。 PHP

转载 作者:可可西里 更新时间:2023-11-01 13:23:32 25 4
gpt4 key购买 nike

我有一系列库存(元素 A 和 B)

项目 A 和 B 以 1 x A 和 2 x B 为一组出售。

这些项目还具有各种属性,这些属性不会影响它们如何分配到集合中。

例如:

$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);

我想重新分配数组 $inventory 以创建 $set(s) 使得

$set[0] => Array
(
[0] => array(A,PINK)
[1] => array(B,RED)
[2] => array(B,BLUE)

)

$set[1] => Array
(
[0] => array(A,MAUVE)
[1] => array(B,YELLOW)
[2] => array(B,GREEN)

)

$set[2] => Array
(
[0] => array(A,ORANGE)
[1] => array(B,BLACK)
[2] => NULL

)

$set[3] => Array
(
[0] => array(A,GREY)
[1] => NULL
[2] => NULL

)

如您所见。这些项目按照它们在库存中出现的顺序重新分配,以创建一组 1 x A 和 2 x B。创建该组时颜色无关紧要。但是我需要能够在创建 $set 数组后找出哪个颜色进入哪个集合。集合被创建,直到所有库存都用完。如果不存在无法进入集合的库存项目,则会插入 NULL 值。

提前致谢!

最佳答案

我假设所有 A 都在所有 B 之前:

$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);

for($b_start_index = 0;$b_start_index<count($inventory);$b_start_index++) {
if($inventory[$b_start_index][0] == 'B') {
break;
}
}

$set = array();
for($i=0,$j=$b_start_index;$i!=$b_start_index;$i++,$j+=2) {
isset($inventory[$j])?$temp1=$inventory[$j]:$temp1 = null;
isset($inventory[$j+1])?$temp2=$inventory[$j+1]:$temp2 = null;
$set[] = array( $inventory[$i], $temp1, $temp2);
}

关于php - 如何将一个数组重新分配到某个 "shape"的另一个数组中。 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3598012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com