按每个组中的前缀和连接后缀对一维数组的值进行分组

问题描述 投票:0回答:2

我有一个由用户输入提供的平面索引数组。我需要合并管道之前具有相同值的值。当第一次遇到前缀时,新值的后缀应附加到先前的值并用逗号分隔。

Array
(
    [0] => 1|1
    [1] => 1|2
    [2] => 1|3
    [3] => 1|4
    [4] => 1|5
    [5] => 1|6
    [6] => 1|32
    [7] => 1|35
    [8] => 2|1
    [9] => 2|5
    [10] => 3|1
    [11] => 3|8
    [12] => 3|11
    [13] => 3|13
    [14] => 3|35
)

想要的结果:

Array
(
    [0] => 1|1,2,3,4,5,6,32,35
    [1] => 2|1,5
    [2] => 3|1,8,11,13,25
)
php arrays concatenation grouping prefix
2个回答
1
投票

使用

$_POST
分隔符循环遍历
explode
|

$array = array('1|1','1|2','2|1','2|5','3|1','3|8');
//simplified version of your array

$new_array = array();
//define a new array  that will be built in the loop below in your desired format

foreach($array as $item){ //loop through original array

    $parsed_item = explode('|',$item); 
   //explode each item to split elements using the | as delimiter

    if(isset($new_array[$parsed_item[0]])){
         //if $new_array with the current key already exists add new value to existing array (concatenate with a comma to existing value)
        $new_array[$parsed_item[0]] = $new_array[$parsed_item[0]].','.$parsed_item[1];

    }else{ 
        //else create new value on array
        $new_array[$parsed_item[0]] = $parsed_item[0].'|'.$parsed_item[1];
    }
}

0
投票

用管道分割每个遇到的字符串。使用前缀来分组。每次遇到新组时,将组引用推送到结果数组中,并将整个输入字符串作为默认值。 当再次遇到组时,仅附加输入字符串中的后缀(以逗号分隔)。 这将直接产生所需的索引结果数组。 演示

$result = [];
foreach ($array as $v) {
    [$group, $value] = explode('|', $v, 2);
    if (!isset($ref[$group])) {
        $ref[$group] = $v;
        $result[] =& $ref[$group];
    } else {
        $ref[$group] .= ",$value";
    }
}
var_export($result);

输出:

array (
  0 => '1|1,2,3,4,5,6,32,35',
  1 => '2|1,5',
  2 => '3|1,8,11,13,35',
)
© www.soinside.com 2019 - 2024. All rights reserved.