我正试图从2条sql语句中提取两个结果,并打印到HTML表中。但有些结果并不正确。请帮助我解决问题。
下面是代码第二个结果没有打印正确的结果-重复的结果。
<?php
global $wpdb;
$result1=$wpdb->get_results("select post_name,id,cat from wp_posts where post_name like '%java%');
$result2=$wpdb->get_results("select post_name,id,cat from wp_posts where post_name like '%oracle%');
?>
<table id="table_id">
<thead>
<tr>
<th>JAVA</th>
<th>ORACLE</th>
</tr>
</thead>
<tbody>
<?php foreach($result1 as $rows1) { ?>
<?php foreach($result2 as $rows2) { ?>
<tr>
<td> <?php echo $rows1->post_name ; ?> </td>
<td> <?php echo $rows2->post_name ; ?> </td>
</tr>
<?php
}
?>
<?php
}
?>
global $wpdb;
$result1=$wpdb->get_results("SELECT post_name,id,cat FROM wp_posts WHERE post_name LIKE '%java%'");
$result2=$wpdb->get_results("SELECT post_name,id,cat FROM wp_posts WHERE post_name LIKE '%oracle%'");
在获取对象之后,我们将所需的值放在两个数组中,这样我们就可以创建一个多维数组。
$result_one = array();
$result_two = array();
//putting values in array
foreach ($result1 as $result) {
$result_one[] = $result->post_name;
}
foreach ($result2 as $result) {
$result_two[] = $result->post_name;
}
//Creating a multi-dimensional array so that we can print two columns easily
$results = array(
$result_one,
$result_two,
);
//Initialising the variables to be used as counters and array indexes.
$i = 0; $j = 0; $k = 0; $p = 1;
//getting length of array
$array_length = count($result_one);
现在启动两个循环,从创建的多维数组中提取数据。在这种情况下:为了正确地创建表,我们需要按以下顺序的值:
$results[0]、$results[1][0]、$results[0][1]、$results[1][1],$results[0][2]、$results[1][2]等等。
因此,我们必须相应地创建循环。
while ($i < 2) {
while ($j < $array_length) {
if (fmod($p,2)) echo '<tr>'; // So that <tr> will be printed only after two <td>
echo "<td>". $results[$i][$j]. "</td>";
if($i == 0) { $i = 1; } else { $i =0; } // Toggling values of $i from 0 to 1.
$k++;
if(fmod($k, 2) == 0){ $j ++; } // Increasing $j after 2 steps.
$p++;
if (fmod($p,2)) echo '</tr>';
}
$i ++;
}
如果您需要三列:
重复步骤一、二和三,这样您就可以创建这样的数组:
$results = array(
$result_one,
$result_two,
$result_three,
);
先将while循环更改为
while ($i < 3)
并将以下语句更改为:
if (fmod($p,3)) echo '<tr>';
if($i == 0) { $i = 1; } elseif ($i == 1) {$i=2} else { $i = 0; }
if(fmod($k, 3) == 0){ $j ++; }
if (fmod($p,3)) echo '</tr>';
我希望你现在能更好地理解,并能自己做出必要的改变。
这似乎很复杂。但这应该奏效。请尝试。任何人都可以随意编辑while循环,使其更简单。
我在第三个结果数组中错过了一些东西。请纠正我。
$results = array(
$result_one,
$result_two,
$result_three,
);
$i = 0; $j = 0; $m = 0; $k = 0; $p = 1;
$array_length = count($result_one);
?>
<table id="table_id">
<thead>
<tr>
<th>ORACLE</th>
<th>JAVA</th>
<th>SAP</th>
</tr>
</thead>
<tbody>
<?php while ($i < 3) {
while ($j < $array_length) {
if (fmod($p,3)) echo '<tr>';
echo "<td>" . $results[$i][$j] . "</td>";
if($i == 0) { $i = 1; } elseif ($i == 1) {$i=2} else { $i = 0; }
$k++;
if(fmod($k, 3) == 0){ $j ++; }
$p++;
if (fmod($p,3)) echo '</tr>';
}
$i ++;
}
?>