Search code examples
phparrayssortingexplode

Group same values in array using explode or similar method


I have this string :

$a="house1,car1,phone1*house2,car2,phone2*house3,car1,phone3*house4,car3,phone3*";

And i want show in order, the house with the same car, as you can se the element that repeat it´s called "car1"

I want get this :

CAR 1 IN THIS HOUSE
    house1,car1,phone1
    house3,car1,phone3

CAR 2 AND  3 IN HOUSES 2 AND 4   
    house2,car2,phone2
    house4,car3,phone3

As you can see, the car1 repeat in 2 houses with different name, and i want order results in this way

I try do this in many ways, use array_diff, array_unique in foreach loop with explode and array_intersect, and results very bad

If somebody can help me here, thank´s, because i don´t know how i can comparate and show results as i put until

Thank´s in advanced and regards community


Solution

  • Try this (tested in php 5.6):

    <?php
    
    // input string
    $a="house1,car1,phone1*house2,car2,phone2*house3,car1,phone3*house4,car3,phone3*";
    
    // split on '*' to get tuples
    $tuples = explode('*', $a);
    
    // ignore empty tuples (trailing '*' in input string)
    $tuples = array_filter($tuples);
    
    // split each tuple on ',' to get individual values
    function splitTuples($tuple) {
        return explode(',', $tuple);
    }
    $tuples = array_map('splitTuples', $tuples);
    
    // sort tuples by the 2nd value
    function sortArraysBySecondValue($a, $b) {
        if ($a[1] < $b[1]) {
            return -1;
        }
        if ($a[1] > $b[1]) {
            return 1;
        }
        return 0;
    }
    usort($tuples, 'sortArraysBySecondValue');
    
    // print tuples
    foreach ($tuples as $tuple) {
        echo implode(',', $tuple) . "\n";
    }
    

    Output is:

    house1,car1,phone1
    house3,car1,phone3
    house2,car2,phone2
    house4,car3,phone3