SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Making multidimensional arrays single dimension

    I have a an array that looks like this
    PHP Code:
    array0array1("values0"), array2("values1")) 
    What I can't figure out is how I get the values from array2 in a new array or a foreach loop.

    It's probably quite obvious and I am just being slow today...

    Thanks

  2. #2
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Code PHP:
    foreach ($array0 as $sub)
    {
       foreach ($sub as $v)
       {
               $newarray[] = $v;
       }
    }
     
    print_r($newarray);

  3. #3
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,031
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    Or, as a general function:

    Code PHP:
    function array_flatten($array)
    {
      $newArray=array();
      foreach($array as $value)
      {
        if (is_array($value))
           $newArray=array_merge($newArray, array_flatten($value));
        else
           $newArray[]=$value;
      }
    }
    var_dump(array_flatten($array));
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  4. #4
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks loads to both of you.

    It's been a long day...

  5. #5
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wonshikee View Post
    Code PHP:
    foreach ($array0 as $sub)
    {
       foreach ($sub as $v)
       {
               $newarray[] = $v;
       }
    }
     
    print_r($newarray);
    Ok, I tried that. After the first foreach loop $sub contains the keys and values of array1() but I want array2().

    How do I get that one?

  6. #6
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Found it. Completely obvious.
    PHP Code:
    $newarray array_values($array0[1]); 


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •