开发者

Need help in php associative array

I have a associative array and i wanted to print out all the column values at once rather by each row

Example if i have a array of

1开发者_StackOverflow中文版.1, 1.2, 1.3, 1.4 
2.1, 2.2, 2.3, 2.4 
3.1, 3.2, 3.3, 3.4 

Currently is displaying 1.1 1.2 1.3 1.4 then 2.1 2.2 2.3 2.4 ...etc

but I wanted to display 1.1 ,2.1, 3.1 then 1.2 2.2 3.2 ... etc

In c++ i know you have to use nested for loop in order to achieve this

for (int i=0; i< col_size; i++) 
{ 
    for (int j=0; j < row_size; j++) 
    { 
        cout << a[i][j]; 
    } 
} 

But how can it be done using associative array in PHP?

Thanks so much!


<?php
$array = array(array(1.1, 1.2, 1.3, 1.4), array(2.1, 2.2, 2.3, 2.4), array(3.1, 3.2, 3.3, 3.4));


$_rows = sizeof($array);
$_cols = sizeof($array[0]);

for ($i=0; $i<=$_cols; $i++) 
  {
    for($j = 0;$j<=$_rows; $j++)
      {
        echo $array[$j][$i]. " ";
      }
      echo " \n";
  }
?>

Outputs

1.1 2.1 3.1    
1.2 2.2 3.2    
1.3 2.3 3.3    
1.4 2.4 3.4    

See http://codepad.org/I2AysS5X

Note the [$j][$i] instead of [$i][$j]


Something like this?

for ($i=0; $i< col_size; $i++) 
{ 
    for ($j=0; $j < row_size; $j++) 
    { 
        echo $a[$i][$j]; 
    } 
} 

;-)

While the above doesn't work for an associative array, you'd have to specify the associations.

For example, if the keys for X are in array $foo and the keys for Y are in $bar, you could do it like this:

$foo = array('a', 'b', 'c', ...);
$bar = array('1', '2', '3', ...);

foreach ($foo => $x) 
{ 
    foreach ($bar => $y) 
    { 
        echo a[$x][$y]; 
    } 
} 

You can extract the keys using array_keys().


for (int $i=0; $i< $col_size; $i++) 
{ 
    for (int $j=0; $j < $row_size; $j++) 
    { 
        echo a[i][j]; 
    } 
} 

just noticed that u didnt use $

wich is a syntax error

but the php and c++ arrays are too close

and every thing u do in c++

can be done the same way in php just don't forget the $ in variable names

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜