PHP 将数组组合在一起,基于键值是相同的


php group array together based on key value being the same

>我有以下数组

Array
(
[0] => Array
    (
        [id_product_option] => 1
        [id_option] => 1
        [id_product] => 3
        [option_value] => White
        [option_name] => color
    )
[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [option_name] => size
    )
[2] => Array
    (
        [id_product_option] => 3
        [id_option] => 1
        [id_product] => 3
        [option_value] => Blue
        [option_name] => color
    )
)

我需要做的是遍历它并找到id_option值匹配的值并将它们分组到一个看起来像

Array
(
[0] => Array
    [0] => Array
        (
            [id_product_option] => 1
            [id_option] => 1
            [id_product] => 3
            [option_value] => White
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )
    [1] => Array
        (
            [id_product_option] => 3
            [id_option] => 1
            [id_product] => 3
            [option_value] => Blue
            [additional_cost] => 0
            [is_active] => 1
            [created_on] => 2014-11-15 01:29:35
            [option_name] => color
            [option_text] => Color
        )
[1] => Array
    (
        [id_product_option] => 2
        [id_option] => 2
        [id_product] => 3
        [option_value] => 9oz
        [additional_cost] => 0
        [is_active] => 1
        [created_on] => 2014-11-15 01:29:35
        [option_name] => size
        [option_text] => Size
    )

)

其中,带有id_option 1 的选项组合在一起

我尝试了以下方法,但没有运气

    $groupOptions = array();
    $prev = "";
    foreach($productOptions as $key=>$options) {
        $id_option = $options['id_option'];
        if($id_option != $prev) {
            $groupOptions[] = $productOptions[$key];
        }
        $prev = $id_option;
    }

你应该使用该id_option作为新数组中的键,否则你将不得不在新数组中搜寻以找到匹配项的位置,这已经在第一个循环中做了

$newarray = array();
foreach($oldarray as $item) {
   $newarray[$item['id_option']][] = $item;
}

我已经用你的例子测试过,似乎工作正常:

$notFactored; # you should provide here your input array
$factored = array();
foreach($notFactored as $nf) {
    $found = FALSE;
    foreach($factored as &$f) { # passed by address !
        if(!empty($f[0]) && $nf['id_option'] == $f[0]['id_option']) {
            $f[] = $nf;
            $found = TRUE;
            break;
        }
    }
    if(!$found) {
        $factored[count($factored)][] = $nf;
    }
}
print 'my factored array : ' . print_r($factored);

希望对:)有所帮助