开发者

How do I iterate through this loop Get each Item Separately

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"
    }
   }


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


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


With foreach loops...

foreach ($array as $key=>$value) 
{
   foreach ($array[$key] as $subkey=>$subvalue) 
   {
      echo "$subkey $subvalue\n";
   }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜