SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: adding to array

  1. #1
    SitePoint Evangelist
    Join Date
    Dec 2005
    Posts
    527
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    adding to array

    Hello I have a loop like this :

    Code:
    foreach ( $big_array as $big_array_field ){
    //some codes
    $news_array[]['name'] = $big_array_field['name'];
    $new_array[]['counter'] = $big_array_field['id']+12;//only a sample , operation is not important
    $new_array[]['id'] = $i++;
    }
    I need a result like this :

    Code:
    $new_array[0]['name'] = any value
    $new_array[0]['counter'] = any value
    $new_array[0]['id'] = any value
    but my code return

    Code:
    $new_array[0]['name'] = any value
    $new_array[1]['counter'] = any value
    $new_array[2]['id'] = any value

    Whats going wrong in my code ?
    and what should I do ?

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Each time you use $news_array[] you add a new element to the end of $news_array.

    You could do it like this:
    PHP Code:
    $cnt 0;
    foreach (
    $big_array as $big_array_field){
        
    $new_array[$cnt]['name'] = $big_array_field['name'];
        
    $new_array[$cnt]['counter'] = $big_array_field['id']+12;
        
    $new_array[$cnt]['id'] = $i++;
        ++
    $cnt;

    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $new_array[] = array('name' => whatever'counter' => blah etc); 


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
  •