如何在php中转换数组的元素结构

时间:2011-07-22 12:07:14

标签: php arrays

我有一个m X n矩阵

$a[0] [0] =" 4889-m.jpg";
$a[0] [1] ="  8675-m.jpg ";

$a[1] [0] ="  image/jpeg ";
$a[1] [1] ="  image/jpeg ";

$a[2] [0] ="C:\wamp\tmp\php9907.tmp ";
$a[2] [1] ="C:\wamp\tmp\php9908.tmp ";

$a[3] [0] ="";
$a[3] [1] ="";

$a[4] [0] =0;
$a[4] [1] =0;

$a[5] [0] = ;
$a[5] [1] =8005 ;

我想将其转换为n X m矩阵

  $a[0][0=" 4889-m.jpg";
  $a[0][1]="  image/jpeg ";
  $a[0][2]="C:\wamp\tmp\php9907.tmp ";
  $a[0][3]="";
  $a[0][4]=0;
  $a[0][5]=13416;

  $a[1][0=" 8675-m.jpg ";
  $a[1][1]="  image/jpeg ";
  $a[1][2]="C:\wamp\tmp\php9908.tmp ";
  $a[1][3]="";
  $a[1][4]=0;
  $a[1][5]=13416;

我也只有$ a它的尺寸也是未知的。

谢谢你的帮助。

3 个答案:

答案 0 :(得分:4)

//Get the count of the results in the array
$n = count($a);
//then for each item in the array loop
while($c = 0; $c =< $n; $c++){
   //get the number of each subitems in the array
   $nc = count($array[$c];
   //then again loop for each subitem in the array
   for($ni = 0; $ni =< $nc; $ni++){
       //then create a new array and set the items as nX
       $newarray[$ni][$nc] = $a[$ni];
   }
   //unset the $nc counter or it will be reset it self when it loops again
   unset($nc);

}

答案 1 :(得分:3)

我认为最简单的方法就是直接在PHP中完成:

foreach ($a as $i => $row) 
    foreach ($row as $j => $val)
    {
        $b[$j][$i] = $val
    }

答案 2 :(得分:2)

这样做:

$b = array();
foreach( $a as $sub1 ) {
    foreach( $sub1 as $key => $value ) {
        $b[ $key ][] = $value;
    }
}