php - 在表中显示两个不同大小的数组

标签 php arrays for-loop html-table

我有两个不同大小的数组,想在同一个表格中并排显示它们。

我试图在一个循环中运行两个数组,但问题是较短的数组用完了索引。

这是我尝试过的:

$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/

相关文章:

php - 路由中间的可选参数

php - JQuery 下拉菜单与 MySQL

php - 连接三个表

javascript - 代码点火器 : route doesn't work when calling php script through AJAX

Java:为什么我不断收到此方法的 StringIndexOutOfBoundsException?

python - for mysql id 字典中的循环与值

java - 在数组开头获取 NullPointerException?

c - 如何将短整数视为 C 中的元素数组?

c - 通过引用传递二维数组

r - 如何循环遍历 lmerTest 输出列表以提取偏差分量