tags:

views:

61

answers:

4

I have this array I want to get the Values "ABC" ,"1","2" and so on respectively and store them in separate variables. I have used nested foreach but could not get it

    array(2) {
       [0] => array(3) {
          [0] => string(10) "ABC"
          [1] => string(1) "1"
          [2] => string(2) "2"
     } [1] => array(3) {
          [0] => string(10) "BCD118"
          [1] => string(1) "1"
          [2] => string(2) "9"
    }
   }
A: 

Your array is of dimensions [2][3], so you should be able to do:

for($i = 0; $i < 2; $i++)
{
for($o = 0; $o < 3; $o++)
{
$variable = $array[$i][$o];
}
}

or an equivalent expression with foreach statements, depending on what you're trying to accomplish.

There are of course limitations from this, as you can really only write into another array. To get them into separate variables, you may just need to reference them statically.

shmeeps
A: 

With foreach loops...

foreach ($array as $key=>$value) 
{
   foreach ($array[$key] as $subkey=>$subvalue) 
   {
      echo "$subkey $subvalue\n";
   }
}
Mike C
How do assign the Key name with a string and its value and put in a session
Derby
See brian d's response
Mike C
+3  A: 

You could use a recursiveiteratoriterator:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

foreach ($it as $key => $value) {
    echo $key . " - " . $value."\n";
}

Would give you:

0 - ABC
1 - 1
2 - 2
0 - BCD118
1 - 1
2 - 9
ircmaxell
+1 for SPL usage. OO power!! ;)
xPheRe
@ircmaxell:How Can i solve this "You would need unique keys though or (for instance) 'BCD118' and 'ABC' would both be key 0 and so 'ABC' would be overwritte"
Derby
+1  A: 

Based on your $_SESSION comment to Mike C,

foreach( $outer_array as $outer_key => $inner_array ) 
{
   foreach( $inner_array as $key => $value ) 
   {
      $_SESSION[$outer_key.'-'.$key] = $value;
   }
}

You would need unique keys though or (for instance) 'BCD118' and 'ABC' would both be key 0 and so 'ABC' would be overwritten.

Edit You could append the $outer_key to the inner $key to get a unique $_SESSION key

This would produce key/value pairs

0-0 : ABC
0-1 : 1
0-2 : 2
1-0 : BCD118
1-1 : 1
2-2 : 9
brian_d
@brianD:How can i overcome this situation
Derby
I have edited my answer to show one possible way
brian_d
@braind: I have my Custom Session Function available so when iam looping it i have to assign it to only the value .So in that array i need to get each value key[0][0] should give me "ABC" so that i can set the the value ABC to one field
Derby
I don't think I quite follow what you are trying to do. But in any case, you should aim to have array keys that describe the value that they contain, especially for $_SESSIONS
brian_d