【问题标题】:Multidimensional array with random removal of key values with minimum 1 left随机删除键值的多维数组,至少剩下 1 个
【发布时间】:2013-07-20 07:55:10
【问题描述】:

我想创建一个数组,我可以随机删除 [id] 键的内容,其中它们是相同的 [parent_id]。

这是我的数组:

数组
(
    [0] => 数组
        (
            [parent_id] => 1
            [id] => 286
        )

    [1] => 数组
        (
            [parent_id] => 286
            [id] => 142
        )

    [2] => 数组
        (
            [parent_id] => 1
            [id] => 287
        )

    [3] => 数组
        (
            [parent_id] => 1
            [id] => 288
        )

    [4] => 数组
        (
            [parent_id] => 1
            [id] => 289
        )

    [5] => 数组
        (
            [parent_id] => 289
            [id] => 140
        )

    [6] => 数组
        (
            [parent_id] => 289
            [id] => 143
        )

    [7] => 数组
        (
            [parent_id] => 289
            [id] => 242
        )

)

我用以下代码生成了它:

$parentList = array();
foreach ($list as $item) 
{
    $parentList[] = array("parent_id" => $item->parent_id, "id" => $item->id);
}

我想不通的是如何将数组转换成这个:

数组
(
    [0] => 数组
        (
            [parent_id] => 1
            [id] => 数组 (286, 287, 288, 289)
        )

    [1] => 数组
        (
            [parent_id] => 286
            [id] => 数组 (142)
        )

    [2] => 数组
        (
            [parent_id] => 289
            [id] => 数组 (140, 143, 242)
        )

)

之后,我希望每个 [id] 数组中随机留下的每个父 id 都有一个 id。

我怎样才能做到这一点?

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    如果结果中的键值无关紧要,最好使用parent_id作为键。

    $result = array();
    foreach ($list as $entry) {
        $parent = $entry['parent_id'];
    
        // Make the base entry
        if (!array_key_exists($parent, $result)) {
            $result[$parent]['parent_id'] = $parent;
        }
    
        // Append this entry to the result
        $result[$parent]['id'][] = $entry['id'];
    }
    

    编辑:如果你只想在一个循环中得到这个结果——我现在意识到你可能是这个意思——你可以试试这个:

    $parentList = array();
    foreach ($list as $item) {
        // Make base entry, if it doesn't exist yet
        if (!array_key_exists($item->parent_id, $parentList)) {
            $parentList[$item->parent_id]['parent_id'] = $item->parent_id;
        }
    
        // Append the item id to the parent container
        $parentList[$item->parent_id]['id'][] = $item->id;
    }
    

    【讨论】:

    • 是与否,@Jack... 输出将是相似的。输入的类型是不同的。上面的代码是我编写的 first 版本,它转换了示例数组(包含父项和项 id 的数组数组)。后来我意识到转换其他来源可能更有帮助,所以我在编辑中编写了 second 块。该函数使用原始输入(对象数组)作为源,而不是使用另一个数组。这样,话题发起者可以选择最适合他(或她?)的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多