douhuan1901 2013-04-02 14:06
浏览 51
已采纳

将重复元素组合为多维数组中的数组

I was wondering when working with multimedional arrays, if a certain key is the same, is there a way to combine the contents of other keys into its own array if a certain key is the same?

Something like this:

// name is the same in both arrays
array(
    array(
        'name' => 'Pepsi',
        'store' => 'Over here',
        'number' => '1234567'
    ),
    array(
        'name' => 'Pepsi',
        'store' => 'Over here',
        'number' => '5556734'
    )
)

into something like this

array(
    array(
        'name' => 'Pepsi',
        'store' => array('Over here', 'Over here'),
        'number' => array('1234567', '5556734')
    )
)

The defining key is checking if the name element is the same for the other arrays.

  • 写回答

3条回答 默认 最新

  • dongrongdao8902 2013-04-11 06:16
    关注

    Thanks to Gianni Lovece for her answer but I was able to develop a much simpler solution based on this problem. Just plug in the $result_arr to browse through and the $key you want to use as basis and it immediately outputs a multidimensional array with non-repeating values for repeating elements (see example below).

    function multiarray_merge($result_arr, $key){
    
        foreach($result_arr as $val){
            $item = $val[$key];     
            foreach($val as $k=>$v){
                $arr[$item][$k][] = $v;
            }
        }
    
        // Combine unique entries into a single array
        // and non-unique entries into a single element
        foreach($arr as $key=>$val){
            foreach($val as $k=>$v){
                $field = array_unique($v);
                if(count($field) == 1){
                    $field = array_values($field);
                    $field = $field[0];
                    $arr[$key][$k] = $field;
                } else {
                    $arr[$key][$k] = $field;
                }
            }
        }
        return $arr;
    }
    

    For example, in the sample array for this question, running multiarray_merge($mysample, 'name') returns

    array(
        'Pepsi' => array(
            'name' => 'Pepsi',
            'store' => 'Over here', // String: Not an array since values are not unique
            'number' => array('1234567', '5556734') // Array: Saved as array since values are unique
        )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?