如何将两个表分配到一个数组中,然后使用foreach循环显示它:
TABLE: 1
pcode rate
------------------------------
aaa 10
bbb 5
ccc 4
TABLE: 2
pcode sales
------------------------------
aaa 250
bbb 100
ccc 40
我已经尝试过:
$final=array();
foreach($table1 as $t1)
$final [$t1->code][0] = $t1->rate;
foreach($table2 as $t2)
$final [$t2->code][1] = $t2->sales;
foreach ($final as $c=>$v){
echo "$c $v[0] $v[1]" . "\n"; \\error
}
请建议?
答案 0 :(得分:1)
像这样更改sql
SELECT t1.pcode, t1.rate, t2.sales FROM table1 as t1 INNER JOIN table2 t2 ON t1.pcode = t2.pcode"
如果无法更改sql,最好使用array_merge_recursive。
$tb1 = codeTokey($table1, 'rate');
$tb2 = codeTokey($table2, 'sales');
//change object to
function codeToKey($arr, $valkey){
$ret = array();
foreach($arr as $a){
$ret[$a->code] = $a->$valkey;
}
return $ret;
}
$fin = array_merge_recursive($tb1, $tb2);
答案 1 :(得分:1)
$final=array();
foreach($table1 as $t1)
$final [$t1->code]['rate'] = $t1->rate;
foreach($table2 as $t2)
$final [$t2->code]['sale'] = $t2->sales;
$table='<table><tr>
<td>name</td>
<td>Sale</td>
<td>Purcahse</td>
</tr>';
foreach ($final as $c=>$v){
$table.='<tr>
<td>'.$c.'</td>
<td>'.((isset($v['rate']))?$v['rate']:'').'</td>
<td>'.((isset($v['sale']))?$v['sale']:'').'</td>
</tr>';
}
$table.='</table>';