Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have array like this:

Array
(
      Array
      (
           [0] => xx
           [1] => 123
      )
      Array
      (
           [0] => xx
           [1] => 523
      )
      Array
      (
           [0] => xx
           [1] => 783
      )
      Array
      (
           [0] => yy
           [1] => 858
      )
      Array
      (
           [0] => yy
           [1] => 523
      )
      Array
      (
           [0] => xx
           [1] => 235
      )
)

What I am trying to do is this:

Array
(
      Array
      (
           [0] => xx
           [1] => 123
           [2] => 523
           [3] => 783
           [4] => 235
      )
      Array
      (
           [0] => yy
           [1] => 858
           [2] => 523
      )

)

So, I only need to look for [0], find same values and than remove duplicates and merge other values (unkown number, although here is just one) under same [0] value. If I do this:

$array = [array("xx","123"), array("xx","523"), array("xx","783"),      array("yy","858"), array("yy","523"), array("xx","235")];
$new=array();

$col = array_column($array, 0);

foreach( $array as $key => $value ) {
    if( ($find = array_search($value[0], $col)) !== false ) {
     unset($value[0]);
    $new[$find]= array_merge($array[$find], $value);
    }
}

print_r($new); 

I get this (without all values):

Array
(
[0] => Array
    (
        [0] => xx
        [1] => 123
        [2] => 235
    )

[3] => Array
    (
        [0] => yy
        [1] => 858
        [2] => 523
    )

)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

When number of other values is just one:

$array = [
    ['xx', 123],
    ['xx', 523],
    ['xx', 783],
    ['yy', 858],
    ['yy', 523],
    ['xx', 235],
];


$result = [];
foreach ($array as $row) {
    list($key, $value) = $row;
    if (!array_key_exists($key, $result)) {
        $result[$key] = [$key];
    }
    $result[$key][] = $value;
}

More generic solution for any number of other values:

$array = [
    ['xx'],
    ['xx', 523],
    ['xx', 783, 111],
    ['yy', 858, 222, 333],
    ['yy', 523, 444, 555, 666],
    ['xx', 235, 777, 888],
];

$result = [];
foreach ($array as $row) {
    $key = array_shift($row);
    if (!array_key_exists($key, $result)) {
        $result[$key] = [$key];
    }
    $result[$key] = array_merge($result[$key], $row);
}

Also, in the last case array_merge() may be replaced by array_push() with unpacked arguments:

if (sizeof($row) > 0) {
    array_push($result[$key], ...$row);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...