Ali Rasheed
Ali Rasheed

Reputation: 2817

Sorting out associative arrays according to values

In each element of the array, the second value points to the parent of the element itself. So for instance in the first array, "City" is the root element and "Area" is the first child, because the second "Area" element (1) points to the key of "City.

Sample data

$locations = array(
    3 => array("Building", 2),
    2 => array("Area", 1),
    0 => array("Floor", 3),
    1 => array("City"),
    4 => array("Room", 0),

    13 => array("Building1", 12),
    12 => array("Area1", 11),
    14 => array("Room1", 10),
    10 => array("Floor1", 13),
    11 => array("City1")
);

Expected output

Room > Floor > Building > Area > City

Room1 > Floor1 > Building1 > Area1 > City1

My solution

$route = [];

foreach ($locations as $locationKey => $locationArray) {

    if (!isset($locationArray[1])) continue;

    $nextLocation = $locations[$locationArray[1]][0];
    $route[] = $nextLocation;
}

But, it wouldn't add array with no index given in array for instance, index 4 array("room", 0);

Also, I cannot figure out how to split the routes if one route is finished

Output I am getting:

Array
(
[0] => Area
[1] => City
[2] => Building
[3] => Floor
[4] => Area1
[5] => City1
[6] => Floor1
[7] => Building1
)

Upvotes: 3

Views: 70

Answers (1)

dWinder
dWinder

Reputation: 11642

You can do this:

First save dictionary for how to get for each node and the roots:

$dic = [];
$roots = [];
foreach($locations as $k => $e) {
    if (count($e) == 2)
        $dic[$e[1]] = $k;
    else
        $roots[] = $k;
}

Then loop for all root and create path:

foreach($roots as $root) {
    $path = [];
    $node = $root;
    while (isset($dic[$node])) {
        $path[] = $locations[$node][0];
        $node = $dic[$node];
    }
    $path[] = $locations[$node][0];
    echo implode(",", array_reverse($path)) . PHP_EOL;
}

Live example: 3v4l

Upvotes: 5

Related Questions