【问题标题】:Reording array by index of first key?按第一个键的索引重新排列数组?
【发布时间】:2023-03-06 20:34:01
【问题描述】:

我想重新排序我的元素索引对齐数组,以便我可以获取每个唯一 CATEGORY 的元素,而不是手动按索引。

前置条件

$products = array(
    'CATEGORY' =>
    array(
        0 => 'book',
        1 => 'book',
        2 => 'desk',
    ),
    /* FYI: Other keys have been removed for conciseness */
    'DESCRIPTION' => 
    array(
        0 => 'Bar',
        1 => 'sdfadasfdasfas',
        2 => 'Barrrr',
    ),
);

后置条件

$products = array(
    'CATEGORY' =>
    array(
        'book' =>
        array(
            0 =>
            array(
                'DESCRIPTION' => 'Bar',
            ),
            1 =>
            array(
                'DESCRIPTION' => 'sdfadasfdasfas',
            ),
        ),
        'desk' =>
        array(
            0 =>
            array(
                'DESCRIPTION' => 'Barrrr',
            ),
        ),
    ),
)

尝试

$cat_to_index = '';

foreach (array_values(array_unique($products['CATEGORY'])) as $category => $uniq_cat) {
    for($i=array_search($uniq_cat, $products['CATEGORY']);
        $i!==FALSE; $i=array_search($uniq_cat, $products['CATEGORY']))
            $cat_to_index .= $i; // just for debugging
}

查看在codepad上运行。

错误

内存不足(无限循环)。最好寻找O(n) 解决此问题的方法。

【问题讨论】:

  • 另外我不明白为什么这不能在O(n) 中完成,其中n$products 的大小...
  • 在我的手机上,所以我只是略过一遍:使用 array_keys 然后使用 array_count_values 怎么样?
  • for ($i = array_search(...)) - 只是随机地将语法放在一起通常是行不通的......:P
  • 在 C++ 和 Python 中使用随机语法!

标签: php arrays search


【解决方案1】:
<?php
$products = array(
    'CATEGORY' =>
    array(
        0 => 'book',
        1 => 'book',
        2 => 'desk',
    ),
    /* FYI: Other keys have been removed for conciseness */
    'DESCRIPTION' => 
    array(
        0 => 'Bar',
        1 => 'sdfadasfdasfas',
        2 => 'Barrrr',
    ),
);

$newProducts = array();
$newProducts['CATEGORY'] = array();
foreach ($products['CATEGORY'] as $id =>$cat) {
    $newProducts['CATEGORY'][$cat] []= array('DESCRIPTION' => $products['DESCRIPTION'][$id]);
}

var_dump($newProducts);

【讨论】:

    【解决方案2】:

    也许array_keys 函数可以帮助处理 $search_value 参数。我希望这是你想要的:

    <?php
    $catalogue_html = '';
    
    // $unique_cats just contains the unique category names
    
    foreach ($uniq_cats as $category => $uniq_cat) {
        // Using the SEARCH param of the "array_key" function
        $keys = array_keys( $products['CATEGORY'] , $uni_cat );
    
        if ( 0 < count( $keys ) ) {
            // Occur more than once
            $catalogue_html .= join(", ", $keys) . "\n";
        }
    }
    
    echo $catalogue_html;
    ?>
    

    【讨论】:

    • 谢谢,但这并不是我想要的。如何将 your output 改为嵌套数组? - 我需要能够在顶层使用CATEGORY 创建一个新数组...
    • 我不知道你想要。但是,如果您正在寻找独特的 $key 在哪里可以找到 CATEGORY $keys 应该是结果。 $catalogue_html .= join(", ", $keys) . "\n"; 是您必须进行计算的地方。
    猜你喜欢
    • 2013-04-02
    • 2017-04-08
    • 1970-01-01
    • 2018-05-17
    • 2011-03-01
    • 2020-02-21
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    相关资源
    最近更新 更多