基于键交替数组中的元素

问题描述 投票:0回答:1

基本上,我有一个包含其他数组作为其值的数组。这些“子”数组中的每一个都被映射。

例如:

$items = [
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
];

现在,每种类型可以有任意数量,但顺序不同。例如,

$items
中的第一项可能是类型 1,接下来的 4 个属于类型 2,接下来的 8 个又属于类型 1,依此类推。请记住,我的实际代码有 8 种不同类型作为可能值,上面只是一个示例。

基本上,我试图定义一个设定的限制 - 比方说,3。按升序排列,并且还按类型升序排序(因此从类型 1 的项目开始,然后是 2,然后 3 等,然后重新启动),我想基本上用类型 1 来“回显”前 3 个项目的“类型”,然后继续执行类型 3 的 3 个项目,依此类推,直到完成类型 8 的 3 个项目。然后,我想要移回数组,然后再次执行此操作,但仅限于我尚未使用的项目,并执行相同的操作。

我想这样做,直到我用完数组中的每个项目为止。

我已经搜索过网络,甚至在 Stackoverflow 上,我似乎找不到一个算法来匹配我想要做的事情。我似乎找不到太多,我开始怀疑我正在寻找的算法是否实际上还不存在,但我可能是错的,或者只是在错误的地方搜索。

我当前的思考过程是使用一个名为

$groups
的单独数组,使用
foreach
循环八次不同的时间,并且在每次循环中,如果不适合特定类型,则继续循环。例如:

// My above $items array example here

// Initialize $groups
$groups = [];

// foreach for type 1
foreach ($items as $item) {
    // If any of the items are not of type 1, ignore and continue
    if ($item["type"] !== 1) {
        continue;
    }
    // Otherwise, push to $groups
    array_push($groups, $item["type"];
}

// foreach for type 2
foreach ($items as $item) {
    // If any of the items are not of type 2, ignore and continue
    if ($item["type"] !== 2) {
        continue;
    }
    // Otherwise, push to $groups
    array_push($groups, $item["type"];
}

// Do this for each possible type, up to type 8

这至少会使

$groups
implode("", $groups)
的输出类似于:
1111111122222222333333334444444555555556666677777777888
但这不仅看起来效率极低且落后,我只是觉得有更好的方法来解决它或我缺少的另一个角度。我完全被难住了。

为了进一步解释,我希望输出更像这样:

111222333444555666777888111222333444555666777888

php arrays algorithm sorting associative-array
1个回答
0
投票

首先

我似乎找不到一种算法来匹配我想要做的事情。我似乎找不到太多,我开始怀疑我正在寻找的算法是否实际上还不存在

是的,你是对的,它不存在也不应该永远存在,算法不应该存在来输出特定的结果。它应该用于执行特定的行为/功能,而不是实现特定的结果。

但是,您可以使用

uasort
根据数组的键对数组进行排序,如下所示:

$items = [
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 1, "text" => "Type of 1"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
    ["type" => 2, "text" => "Type of 2"],
];

uasort($items, fn ($a, $b) => $a > $b ? 1 : -1); 

print_r($items);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.