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

时间:2021-07-06 20:24:40

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.

定义键是检查name元素是否与其他数组相同。

3 个解决方案

#1


1  

You can try a function like this.

你可以尝试这样的功能。

function mergeByKey($array,$key){
  $tmp_array = array();
  foreach ( $array as $k => $row ) {
    $merged = false;
    foreach ($tmp_array as $k2 => $tmp_row){
       if ($row[$key] == $tmp_row[$key]){
          foreach ( $row as $k3 => $value ) {
            if ($k3 == $key) continue;
            $tmp_array[$k2][$k3][] = $value;
            $merged = true;
          }
       }
       if ($merged) break;
    }
    if (!$merged) {
       $new_row = array();
       foreach ( $row as $k4 => $value ) {
         if ($k4 == $key) $new_row[$k4] = $value;
         else $new_row[$k4] = array($value);
       }
       $tmp_array[] = $new_row;
    }
  }
  foreach ( $tmp_array as $t => $row ) {
    foreach ( $row as $t2 => $value ) {
      if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
    }
  }
  return $tmp_array;
}

passing the array as first parameter and the key as second one. I'm referencing to your array structure

将数组作为第一个参数传递,将键作为第二个参数传递。我正在引用你的数组结构

edited: missed a piece

编辑:错过了一块

edited2: if resultin array contains elements with one string, it returns a string and not a array with one element

edited2:如果resultin数组包含带有一个字符串的元素,则返回一个字符串,而不是一个带有一个元素的数组

demo

演示

#2


1  

This function uses a given field name as the grouping identifier and turns all other fields into arrays.

此函数使用给定的字段名称作为分组标识符,并将所有其他字段转换为数组。

Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)

请注意,单个出现的字段名称将产生具有其他字段的单个元素的数组。我不确定这是否是一个令人满意的特质,但只是确保你知道;-)

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

function mergeArray($array, $column)
{
    $res = array();

    foreach ($array as $item) {
        foreach ($item as $key => $value) {
            if ($key === $column) {
                $res[$column][$key] = $value;
            } else {
                $res[$column][$key][] = $value;
            }
        }
    }
    return array_values($res);
}

print_r(mergeArray($arr, 'name'));

Demo

演示

#3


0  

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).

感谢Gianni Lovece的回答,但我能够根据这个问题开发出更简单的解决方案。只需插入$ result_arr以浏览并使用您想要用作基础的$键,它就会立即输出一个多维数组,其中包含重复元素的非重复值(参见下面的示例)。

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

例如,在此问题的示例数组中,运行multiarray_merge($ mysample,'name')将返回

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
    )
);

#1


1  

You can try a function like this.

你可以尝试这样的功能。

function mergeByKey($array,$key){
  $tmp_array = array();
  foreach ( $array as $k => $row ) {
    $merged = false;
    foreach ($tmp_array as $k2 => $tmp_row){
       if ($row[$key] == $tmp_row[$key]){
          foreach ( $row as $k3 => $value ) {
            if ($k3 == $key) continue;
            $tmp_array[$k2][$k3][] = $value;
            $merged = true;
          }
       }
       if ($merged) break;
    }
    if (!$merged) {
       $new_row = array();
       foreach ( $row as $k4 => $value ) {
         if ($k4 == $key) $new_row[$k4] = $value;
         else $new_row[$k4] = array($value);
       }
       $tmp_array[] = $new_row;
    }
  }
  foreach ( $tmp_array as $t => $row ) {
    foreach ( $row as $t2 => $value ) {
      if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
    }
  }
  return $tmp_array;
}

passing the array as first parameter and the key as second one. I'm referencing to your array structure

将数组作为第一个参数传递,将键作为第二个参数传递。我正在引用你的数组结构

edited: missed a piece

编辑:错过了一块

edited2: if resultin array contains elements with one string, it returns a string and not a array with one element

edited2:如果resultin数组包含带有一个字符串的元素,则返回一个字符串,而不是一个带有一个元素的数组

demo

演示

#2


1  

This function uses a given field name as the grouping identifier and turns all other fields into arrays.

此函数使用给定的字段名称作为分组标识符,并将所有其他字段转换为数组。

Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)

请注意,单个出现的字段名称将产生具有其他字段的单个元素的数组。我不确定这是否是一个令人满意的特质,但只是确保你知道;-)

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

function mergeArray($array, $column)
{
    $res = array();

    foreach ($array as $item) {
        foreach ($item as $key => $value) {
            if ($key === $column) {
                $res[$column][$key] = $value;
            } else {
                $res[$column][$key][] = $value;
            }
        }
    }
    return array_values($res);
}

print_r(mergeArray($arr, 'name'));

Demo

演示

#3


0  

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).

感谢Gianni Lovece的回答,但我能够根据这个问题开发出更简单的解决方案。只需插入$ result_arr以浏览并使用您想要用作基础的$键,它就会立即输出一个多维数组,其中包含重复元素的非重复值(参见下面的示例)。

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

例如,在此问题的示例数组中,运行multiarray_merge($ mysample,'name')将返回

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
    )
);