Array (
[x0] => sometext1
[x1] => sometext2
[x2] => sometext3
[x3] => sometext4
[x4] => sometext5
[x5] => sometext6
[x?] => sometext?
[y0] => someothertext1
[y1] => someothertext2
[y2] => someothertext3
[y3] => someothertext4
[y4] => someothertext5
[y5] => someothertext6
[y?] => someothertext?
)
我正在尝试使用此数组并创建一个表。基本上我不知道有多少x或y ...到目前为止我找不到任何解决方案。任何帮助将不胜感激。
我想要的结果
表
x | y
sometext1 | someothertext1
sometext2 | someothertext2
... | ...
答案 0 :(得分:1)
如果可能的话,对数组进行一次小的修正,告诉它如何声明。让它看起来像这样:
Array (
[x] => Array (
[0] => sometext1
[1] => sometext2
[2] => sometext3
[3] => sometext4
[4] => sometext5
[5] => sometext6
[?] => sometext?
)
[y] => Array (
[0] => sometext1
[1] => sometext2
[2] => sometext3
[3] => sometext4
[4] => sometext5
[5] => sometext6
[?] => sometext?
)
)
通过这种方式,使用PHP,你可以这样做:
<table>
<?php
echo '<tr>';
foreach ($array as $heading => $contents)
echo "<th>$heading</th>";
echo '</tr>';
foreach ($array as $heading => $contents)
foreach ($heading as $value)
echo "<td>$value</td>";
?>
</table>
答案 1 :(得分:1)
试试这个:
<?php
$array = Array('x0' => 'sometext1',
'x1' => 'sometext2',
'x2' => 'sometext3',
'x3' => 'sometext4',
'x4' => 'sometext5',
'x5' => 'sometext',
'y0' => 'someothertext1',
'y1' => 'someothertext2',
'y2' => 'someothertext3',
'y3' => 'someothertext4',
'y4' => 'someothertext5',
'y5' => 'someothertext6',
);
$res = array();
foreach($array as $key=>$val){
preg_match('/(?P<var>\w{1})(?P<ky>\d+)/',$key, $match);
$res[$match['ky']][$match['var']] = $val;
}
echo "<table>";
echo "<tr><td>X</td><td>Y</td></tr>";
foreach($res as $keys=>$vals){
echo "<tr><td>".$vals['x']."</td><td>".$vals['y']."</td></tr>";
}
echo "<table>";
?>
输出:
X Y
sometext1 someothertext1
sometext2 someothertext2
sometext3 someothertext3
sometext4 someothertext4
sometext5 someothertext5
sometext someothertext6
答案 2 :(得分:0)
将该数组复制到另一个var中,对于此示例,您有两个名为$ arr且$ arr2的数组,它们只是每个数组的副本。
$arr = $arr2 = Array ( .... );
foreach($arr as $key=>$data)
{
$num = substr($key,1);
echo '<tr><td>'.$data.'</td>';
foreach($arr2 as $key2=>$data2)
{
$num2 = substr($key2,1);
if($num == $num2)
{
echo '<td>'.$data.'</td>';
break;
}
}
echo '</tr>';
}
如果没有“y”匹配“x”额外的内容,这当然没有考虑修复丢失的td之类的事情。
答案 3 :(得分:0)
正如Praveen Kumar解释的那样,表格如下:
# X y
0 sometext1 sometext1
1 sometext2 sometext2