简体   繁体   中英

PHP Multidimensional Arrray

Im having problems trying to figure out a way in which i can solve the following, where if the elements of the arrays are common to one another they merge to form a new array with each other.

For instance, if I have:

$array = [ [0,4], [1,2], [1,3], [3,2] ]

Then the new array would be like:

$newarray = [ [0,4], [1,2,3] ]

Where the arrays of $array which have elements in common then merge, I've tried a couple of ways like looping through the array and comparing individual elements but just can't get my head around it, any help would be great

Another simple example would be:

$array2 = [ [0,1], [3,4], [4,2], [2,3], [6,5] ];

$newarray2 = [ [0,1], [2,3,4], [5,6]]

thanks

$array2 = [ [0,1], [3,4], [4,2], [2,3], [6,5] ];
$wrk = array_count_values(call_user_func_array('array_merge', $array2));
ksort($wrk);
$result = [];
$prevValue = -INF;
$i = -1;
foreach($wrk as $key => $value) {
    if ($value != $prevValue) {
        $prevValue = $value;
        ++$i; 
    }
    $result[$i][] = $key;
}
var_dump($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM