We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,313 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Convert associative array to indexed array

I have an associative array that is many levels deep. I want to convert it to an indexed array (i.e. remove the key names). I don't want to flatten it; I want it to remain a nested array with all of the values intact. What's the best way to accomplish this?

3
Contributors
3
Replies
13 Hours
Discussion Span
3 Months Ago
Last Updated
31
Views
Question
Answered
Dani
The Queen of DaniWeb
Administrator
21,359 posts since Feb 2002
Reputation Points: 1,555
Solved Threads: 368
Skill Endorsements: 122

Don't think you have to, you can just access it by index as well.

pritaeas
Posting Prodigy
Moderator
9,310 posts since Jul 2006
Reputation Points: 1,178
Solved Threads: 1,465
Skill Endorsements: 86

I quickly put together this recursion function.

function assoc2indexedMulti($arr) {

    // initialize destination indexed array
    $indArr = array();

    // loop through source
    foreach($arr as $val) {

        // if the element is array call the recursion
        if(is_array($val)) {

            $indArr[] = assoc2indexedMulti($val);

        // else add the value to destination array
        } else {

            $indArr[] = $val;
        }
    }

    return $indArr;
}

Tested it on a small array, I hope it works OK on your array. If the array is large it might be an issue since it doubles the memory requirement.

broj1
Nearly a Posting Virtuoso
1,211 posts since Jan 2011
Reputation Points: 167
Solved Threads: 164
Skill Endorsements: 13

Thanks, that worked! :)

Dani
The Queen of DaniWeb
Administrator
21,359 posts since Feb 2002
Reputation Points: 1,555
Solved Threads: 368
Skill Endorsements: 122
Question Answered as of 3 Months Ago by pritaeas and broj1

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.1307 seconds using 2.68MB