我有两个不同大小的数组,想在同一个表格中并排显示它们。
我试图在一个循环中运行两个数组,但问题是较短的数组用完了索引。
这是我尝试过的:
$clean_s = ['apple','ball','cat','dog'];
$clean_r = ['apple','bat','carrot','duck','elephant','fan'];
if(sizeof($clean_s) == sizeof($clean_r)) {
$max = sizeof($clean_s);
} else {
$max = sizeof($clean_s) > sizeof($clean_r) ? sizeof($clean_s) : sizeof($clean_r);
}
$table = '<table><thead><tr><th>Source</th><th>Result</th></thead><tbody>';
for($i=0; $i < $max; $i++) {
$table .= '<tr><td>'.$clean_s[$i].'</td><td>'.$clean_r[$i].'</td></tr>';
}
需要的输出:
Source | Result
________________________
apple | apple
ball | bat
cat | carrot
dog | duck
| elephant
| fan
最佳答案
可以查看isset()在 echo
之前为:
$table = '<table><thead><tr><th>Source</th><th>Result</th></thead><tbody>';
for($i=0; $i < $max; $i++) {
$s = isset($clean_s[$i]) ? $clean_s[$i] : '';
$r = isset($clean_r[$i]) ? $clean_r[$i] : '';
$table .= '<tr><td>'.$s.'</td><td>'.$r.'</td></tr>';
}
PHP 7 也可以使用 $s = $clean_s[$i] 的语法 ?? '';
关于php - 在表中显示两个不同大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784778/