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
)
)
A simple loop using the
0
index as the key for the new array and appending the other values from the1
index:array_values()
to re-index the array to numeric indexes.For uniqueness, just do
array_unique()
in the loop or map it at the end:When number of other values is just one:
More generic solution for any number of other values:
Also, in the last case
array_merge()
may be replaced byarray_push()
with unpacked arguments: