+ Reply to Thread
Results 1 to 3 of 3

Thread: Loop is not working well

  1. #1

    Loop is not working well

    Hello , i have this Nested Array :
    Code:
    Array
    (
        [title] => 
        [description] => true
        [categories] => Array 
              (
                     [0] => 3
                     [1] => 5
              )
        [meta] => 0
    )
    And I am trying to iterate through this loop with the following code:
    Code:
    if (is_array($data) && count($data) >= 1) {
        foreach ($data as $name => $value) {
            if (is_array($value)) {
                foreach ($value as $v) {
                    $data[$name][] = stripslashes($v);  
                }
            } else {
                $data[$name] = stripslashes($value);    
            }
        }
    }
    But when I print_r($data), I am seeing the 2nd level array is looping twice so I am seeing:
    Code:
    Array
    (
        [title] => 
        [description] => true
        [categories] => Array 
              (
                     [0] => 3
                     [1] => 5
                     [2] => 3 // duplicated
                     [3] => 5 // duplicated
              )
        [meta] => 0
    )
    Any ideas why i am getting this ?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    41
    No it's not iterating twice. You are just adding 2 new values instead of replacing existing ones. Try this code , it should solve your issue:
    Code:
    if (is_array($data) && count($data) >= 1) {
        foreach ($data as $name => $value) {
            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    $data[$name][$k] = stripslashes($v);  
                }
            } else {
                $data[$name] = stripslashes($value);    
            }
        }
    }

  3. #3
    Thanks Hassan for your help

+ Reply to Thread

Tags for this Thread

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