【问题标题】:how convert the element structure of an array in php [duplicate]如何在php中转换数组的元素结构[重复]
【发布时间】:2011-10-11 00:16:19
【问题描述】:

我有一个 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 它的尺寸也是未知的。

感谢您的帮助。

【问题讨论】:

标签: php arrays


【解决方案1】:
//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);

}

【讨论】:

    【解决方案2】:

    这样就可以了:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-13
        • 1970-01-01
        • 2019-07-25
        • 2015-10-24
        • 1970-01-01
        • 2011-10-17
        • 2016-02-18
        相关资源
        最近更新 更多