omer Farooq omer Farooq - 3 months ago 11
PHP Question

Efficient way of traversing a complicated Array

I have a database table that would return an array something like this

$roles['admin'] = 'app1,app2,app3';
$roles['moderator'] = 'app2,app3';


Now I want to traverse this array to show in my view, But instead of showing all apps inside each role, i would like to show all roles inside each app.

So ideally i would like the above array to become this

$apps['app1'] = 'admin';
$apps['app2'] = 'admin,moderator';
$apps['app3'] = 'admin,moderator';


I have been trying to solve this for 2 hours now, but for some reason I can't find an efficient way of doing this.

Answer

You can map one array to the other by using array_reduce, array_keys and explode to turn your CSV values into arrays

$apps = array_reduce(array_keys($roles), function($apps, $key) use ($roles) {
    foreach (explode(',', $roles[$key]) as $app) $apps[$app][] = $key; 
    return $apps;
}, []);

Note that the result is slightly different to what you wanted in that the values are themselves arrays instead of comma separated strings.

Array
(
    [app1] => Array
        (
            [0] => admin
        )

    [app2] => Array
        (
            [0] => admin
            [1] => moderator
        )

    [app3] => Array
        (
            [0] => admin
            [1] => moderator
        )

)

If you really need CSV values, add this

$apps = array_map(function($list) {
    return implode(',', $list);
}, $apps);

which produces

Array
(
    [app1] => admin
    [app2] => admin,moderator
    [app3] => admin,moderator
)