-2

我想重新排序我的元素索引对齐数组,以便我可以获取每个唯一的元素,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
}

请参阅在键盘上运行。

错误

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

4

2 回答 2

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);
于 2012-11-06T14:26:47.987 回答
0

Maybe the array_keys function can help with the $search_value param. I hope this is what you want :

<?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;
?>
于 2012-11-06T10:30:58.800 回答