Skip to content
Advertisement

Turning a multidimensional PHP Array into two different arrays [closed]

What I have is:

$choices = [
    ['horror' => ["Rosemary's Baby","Cujo","Children Of The Corn", "Congo"]],
    ['romance' => ["Sleepless In Seattle", "You've Got Mail", "Crazy Rich Asians", "The Notebook"]],
    ['sci_fi' => ["Alien", "Star Trek", "Star Wars", "Space Invaders"]]
];

What I would like to end up with is two arrays:

$genres = ['horror', 'romance', 'sci_fi'];

$collections = [
    ["Rosemary's Baby", "Sleepless In Seattle", "Alien"],
    ["Cujo", "You've Got Mail", "Star Trek"],
    ["Children Of The Corn", "Crazy Rich Asians", "Star Wars"],
    ["Congo", "The Notebook", "Space Invaders"]
];

I’ve been playing around with this for a couple of hours. Any ideas?

Advertisement

Answer

As long as there is only one genre per choice the following works

$genres = $collections = [];
foreach ($choices as $choice) {
    $genres[] = $genre = array_key_first($choice);
    foreach ($choice[$genre] as $i => $title) {
        $collections[$i][] = $title;
    }
}

Otherwise you need to iterate the genres aswell

$choices = [
    [
        'horror' => ["Rosemary's Baby","Cujo","Children Of The Corn", "Congo"],
        'romance' => ["Sleepless In Seattle", "You've Got Mail", "Crazy Rich Asians", "The Notebook"]
    ],
    [
        'sci_fi' => ["Alien", "Star Trek", "Star Wars", "Space Invaders"]
    ]
];

$genres = $collections = [];
foreach ($choices as $choice) {
    foreach ($choice as $genre => $collection) {
        $genres[] = $genre;
        foreach ($collection as $i => $title) {
            $collections[$i][] = $title;
        }
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement