Need help to re-structure this array

Hi every body ,

I have this array


Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
        )
 
    [1] => Array
        (
            [0] => 2
            [1] => 7
            [2] => 9
        )
 
    [2] => Array
        (
            [0] => 1
            [1] => 5
            [2] => 11
        )

    [3] => Array
        (
            [0] => 2
            [1] => 7
            [2] => 9
        ) 
)

I want to make it same as this structure

 
-1
--3
--4
--5
---11
-2
--7
---9

is that possible ??

thanks all

What’s the logic behind your desired outcome?

(What i meant is… how do you decide where to put each number)

I think that I can see the pattern.

If you have 1,3 in one array, and 1,5,11 in another array, those would translate to

-1
–3
–5
—11

Here’s what we start with:



$groups = array(
    array(1, 3),
    array(2, 7, 9),
    array(1, 5, 11),
    array(2, 7, 9) 
);

We can loop through each group of arrays, and place their content in a nested array with the following:


function nestedStructure($groups) {
    $nested = array();
    foreach ($groups as $group) {
        $location = &$nested;
        foreach ($group as $item) {
            if (!isset($location[$item])) {
                $location[$item] = array();
            }
            $location = &$location[$item];
        }
    }
    return $nested;
}

and convert them with:


$nested = nestedStructure($groups);

and finally we can show the new structure with:


function showStructure($groups, $depth=1) {
    foreach ($groups as $index => $group) {
        echo str_repeat('-', $depth) . $index . '<br>';
        if (is_array($group)) {
            showStructure($group, $depth + 1);
        }
    }
}

Here’s the full test code:


<?php
$groups = array(
    array(1, 3),
    array(2, 7, 9),
    array(1, 5, 11),
    array(2, 7, 9) 
);

function nestedStructure($groups) {
    $nested = array();
    foreach ($groups as $group) {
        $location = &$nested;
        foreach ($group as $item) {
            if (!isset($location[$item])) {
                $location[$item] = array();
            }
            $location = &$location[$item];
        }
    }
    return $nested;
}
function showStructure($groups, $depth=1) {
    foreach ($groups as $index => $group) {
        echo str_repeat('-', $depth) . $index . '<br>';
        if (is_array($group)) {
            showStructure($group, $depth + 1);
        }
    }
}

echo 'Before:<br>';
echo '<pre>'; var_dump($groups); echo '</pre>';
echo '<br>';

$nested = nestedStructure($groups);
echo 'After:<br>';
showStructure($nested);
?>

Yes definately we need to know the purpose.
Can you explain a bit more?

Regards