使用关联数组减少数组

时间:2017-07-16 07:57:32

标签: php array-reduce

我有一个像这样的数组

 $filter_array = Array
    (
        [0] => Array
            (
                [fv_id] => 1
                [fv_value] => Red
                [filter_id] => 1
                [filter_name] => Color
            )

        [1] => Array
            (
                [fv_id] => 2
                [fv_value] => Blue
                [filter_id] => 1
                [filter_name] => Color
            )

    )

我想通过在数组顶部使用 filter_name filter_id 来减少数组,这对所有数组都是类似的。

$newArray = array_reduce($filter_array,function($carry,$item){

            $allFilterValues[] = array(
                'fv_id' => $item['fv_id'],
                'fv_value' => $item['fv_value'],
            );

             $formated_array = array(
                'filter_id' => $item['filter_id'],
                'filter_name' => $item['filter_name'],
                'filter_values' => $allFilterValues
            );
            return $formated_array;
        });

但我只是在 filter_values

上获得最后一个数组迭代值
Array
(
    [filter_id] => 1
    [filter_name] => Color
    [filter_values] => Array
        (
            [0] => Array
                (
                    [fv_id] => 2
                    [fv_value] => Blue
                )

        )

)

但我希望数组是这样的。

Array
(
    [filter_id] => 1
    [filter_name] => Color
    [filter_values] => Array
        (
                [0] => Array
                (
                    [fv_id] => 1
                    [fv_value] => Red
                ),

                [1] => Array
                (
                    [fv_id] => 2
                    [fv_value] => Blue
                )

        )

)

1 个答案:

答案 0 :(得分:2)

array_reduce回调函数的每次迭代中,必须返回当前$carry值:

$newArray = array_reduce($filter_array,function($carry,$item){
    // create key so as to distinct values from each other
    $key = $item['filter_id'] . '-' . $item['filter_name'];

    // check if created key exists in `$carry`, 
    // if not - we init it with some data
    if (empty($carry[$key])) {
        $carry[$key] = [
            'filter_id' => $item['filter_id'],
            'filter_name' => $item['filter_name'],
            'filter_values' => []
        ];
    }

    // add values to `filter_values`
    $carry[$key]['filter_values'][] = [
        'fv_id' => $item['fv_id'],
        'fv_value' => $item['fv_value'],
    ];

    return $carry;
}, []);

// if you want to reindex `$newArray` from 0:
$newArray = array_values($newArray);

更新:当且仅当$filter_array 'filter_id''filter_name'的值始终时,您可以简化你的代码:

$newArray = [];
$first = true;
foreach ($filter_array as $item) {
    if ($first) {
        $first = false;
        $newArray = [
            'filter_id' => $item['filter_id'],
            'filter_value' => $item['filter_name'],
            'filter_values' => []
        ];
    }

    $newArray['filter_values'][] = [
        'fv_id' => $item['fv_id'],
        'fv_value' => $item['fv_value'],
    ];
}
echo'<pre>',print_r($newArray),'</pre>';